gpt4 book ai didi

javascript - react Hook setState 参数

转载 作者:行者123 更新时间:2023-11-29 17:35:49 25 4
gpt4 key购买 nike

我想知道以下两个版本的代码之间的区别。两个版本的作用相同。

1) 这里只是counter变量用来获取当前值

const Counter = () => {
const [counter, setCounter] = useState(0);
return <button onClick={() => setCounter(counter + 1)}>{counter}</button>;
}

2) 这个版本传递了一个函数给setCounter

const Counter = () => {
const [counter, setCounter] = useState(0);
return <button onClick={() => setCounter(c => c + 1)}>{counter}</button>;
}

官方文档说:

If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value.

那么第一个选项有什么问题呢?有一些陷阱吗?

最佳答案

对于您的示例中的特定代码,您手头有以前的值,因此没有太大区别。但有时你不会。例如,假设您想要一个内存回调函数。由于内存化,counter 的值在创建闭包时被锁定,并且不会是最新的。

const Counter = () => {
const [counter, setCounter] = useState(0);

// The following function gets created just once, the first time Counter renders.
const onClick = useCallback(() => {
setCounter(c => c + 1); // This works as intended
//setCounter(counter + 1); // This would always set it to 1, never to 2 or more.
}, []); // You could of course add counter to this array, but then you don't get as much benefit from the memoization.

return <button onClick={onClick}>{counter}</button>;
}

关于javascript - react Hook setState 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56615931/

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