为什么当引用的值更新时 useRef 不会更新?

huangapple go评论59阅读模式
英文:

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 + 1nextPage = 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&#39;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(() =&gt; page + 1, [page]);

  return (
    &lt;div&gt;
      &lt;p&gt;{nextPage}&lt;/p&gt;
      &lt;button onClick={() =&gt; setPage((prevPage) =&gt; prevPage + 1)}&gt;
        {page}
      &lt;/button&gt;
    &lt;/div&gt;
  );
}

huangapple
  • 本文由 发表于 2023年7月31日 21:43:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定