为什么需要具有功能更新表单的 React useState? [英] Why React useState with functional update form is needed?

查看:23
本文介绍了为什么需要具有功能更新表单的 React useState?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关功能更新的React Hook 文档,请参阅这句话:

I'm reading React Hook documentation about functional updates and see this quote:

+"和-"按钮使用功能形式,因为更新值基于之前的值

The "+" and "-" buttons use the functional form, because the updated value is based on the previous value

但我看不出需要功能更新的目的是什么,它们与直接使用旧状态计算新状态有什么区别.

But I can't see for what purposes functional updates are required and what's the difference between them and directly using old state in computing new state.

为什么 React useState Hook 的 updater 函数需要函数式更新表单? 有哪些例子我们可以清楚地看到差异(所以使用直接更新会导致错误)?

例如,如果我从文档中更改此示例

For example, if I change this example from documentation

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
    </>
  );
}

直接更新count:

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
    </>
  );
}

我看不出任何行为差异,也无法想象计数不会更新(或不会更新)的情况.因为每当计数发生变化时,都会调用 onClick 的新闭包,捕获最新的 count.

I can't see any difference in behaviour and can't imagine case when count will not be updated (or will not be the most recent). Because whenever count is changing, new closure for onClick will be called, capturing the most recent count.

推荐答案

状态更新在 React 中是异步的.因此,下次更新时 count 中可能会有旧值.例如,比较这两个代码示例的结果:

State update is asynchronous in React. So it is possible that there would be old value in count when you're updating it next time. Compare, for example, result of these two code samples:

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => {
        setCount(prevCount => prevCount + 1); 
        setCount(prevCount => prevCount + 1)}
      }>+</button>
    </>
  );
}

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => {
        setCount(count + 1); 
        setCount(count + 1)}
      }>+</button>
    </>
  );
}

这篇关于为什么需要具有功能更新表单的 React useState?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆