英文:
Why useRef doesn't update when referenced value is updated?
问题
我有一段代码:
const page = useRef(1);
const nextPage = useRef(page.current + 1);
我想知道为什么当我更新page
时,nextPage
不会更新?因为nextPage
引用了正在更新的page.current
吗?
page.current = 5;
英文:
I have a code:
const page = useRef(1);
const nextPage = useRef(page.current + 1);
I was wondering why nextPage
won't update when I update page
? Since nextPage
is referencing page.current
that is getting updated?
page.current = 5;
答案1
得分: 0
如果这个工作按照您的期望进行,那么nextPage = page.current + 1
和nextPage = useRef(page.current + 1)
之间不会有任何区别。
传递给useRef
的参数只在第一次渲染时使用一次,之后它会保持结果直到您改变它。这与引用无关,它只是接受该值如其所是。
英文:
If that was working as you expected, there wouldn't be any difference
between
nextPage = page.current + 1
and nextPage = useRef(page.current + 1)
.
The argument that is passed into useRef
is used only once, on first render, after that it keeps the result until you change it. That has nothing to do with the reference, it just accepts the value as it is
答案2
得分: 0
只需返回代码的翻译部分:
我认为你需要创建一个计算值。
在React中,不应该在DOM上呈现useRef更新...
相反,你应该使用useState钩子,useMemo来计算和呈现,就像这样:
```tsx
function App() {
const [page, setPage] = useState(1);
const nextPage = useMemo(() => page + 1, [page]);
return (
<div>
<p>{nextPage}</p>
<button onClick={() => setPage((prevPage) => prevPage + 1)}>
{page}
</button>
</div>
);
}
<details>
<summary>英文:</summary>
I think you need to create a computed value.
useRef updates isn't supposed to be rendered on the DOM in React...
Instead, you should use useState hook, useMemo to compute and render, like this:
```tsx
function App() {
const [page, setPage] = useState(1);
const nextPage = useMemo(() => page + 1, [page]);
return (
<div>
<p>{nextPage}</p>
<button onClick={() => setPage((prevPage) => prevPage + 1)}>
{page}
</button>
</div>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论