反应挂钩 setState 参数
React hook setState arguments
我想知道下面两个版本代码的区别。两个版本都一样。
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>;
}
我想知道下面两个版本代码的区别。两个版本都一样。
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>;
}