gpt4 book ai didi

reactjs - react set(a) 和 set(a => a) 的区别

转载 作者:行者123 更新时间:2023-12-01 23:10:24 28 4
gpt4 key购买 nike

case1 和 case2 有什么区别?

const [a, setA] = useState(0);

setA(a + 1); //case 1
setA(a => a + 1); //case 2

最佳答案

  • setA(a + 1); 将从当前附件的 a 值更新。
  • setA(a => a + 1); 将从之前的状态值更新

尝试将其中的多个入队并查看差异。

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
};

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
};

如果下一个状态依赖于任何先前的状态,您应该使用功能状态更新。当包含按时间间隔或在数组循环中更新状态的回调时,功能状态更新也很方便。

查看此工作演示:

Edit react - regular and functional state updates

关于reactjs - react set(a) 和 set(a => a) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70031638/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com