繁体   English   中英

在反应钩子中更新 state

[英]Updating state in react hooks

1.

const [count, setCount] = useState(0);

setCount(count+1);

或者

2.

const [count, setCount] = useState(0);

setCount(count => count+1);

我很困惑何时应该在我的组件中使用两种更新 state 的方法,它有什么区别? 谢谢。

当新的 state 独立于以前的 state 时,使用选项 1,例如从服务器获取数据并且您只是替换当前的 state。

当下一个 state取决于当前 state 时,使用选项 2,例如递增计数。

顺便说一句,选项 2 的模式称为功能更新,因为您将其传递给纯 function,它采用当前的 state,对其进行变异,然后返回下一个 Z9ED39E2EA931586B6A985A6942EF53。

以下是我创建的一个计数演示,以真正展示两者之间的区别以及为什么区别很重要。

const [count, setCount] = useState(0);

/**
  * count +3 click handler using naive state updates.
  */
const clickHandler1 = () => {
  // assume count equals some number n
  setCount(count + 1); // update queued, count === n, count = n + 1
  setCount(count + 1); // update queued, count === n, count = n + 1
  setCount(count + 1); // update queued, count === n, count = n + 1
  // when processed the count will be n + 1
};

/**
  * count +3 click handler using functional state updates.
  */
const clickHandler2 = () => {
  // assume count equals some number n
  setCount(count => count + 1); // update queued, count === n + 0, count = prevCount + 1
  setCount(count => count + 1); // update queued, count === n + 1, count = prevCount + 1
  setCount(count => count + 1); // update queued, count === n + 2, count = prevCount + 1
  // now when processed each call uses the result of the previous update
  // count will be n + 1 + 1 + 1, or n + 3
};

编辑反应 - 坏和好的状态更新

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM