简体   繁体   English

反应钩子setState参数

[英]React hook setState arguments

I would like to know the difference between the following two versions of code. 我想知道以下两个版本的代码之间的区别。 Both versions do the same. 两种版本的功能相同。

1) Here just the counter variable is used to get the current value 1)这里只是计数器变量用于获取当前值

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

2) This version passes a function to setCounter 2)此版本将函数传递给setCounter

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

The official documentation says: 官方文件说:

If the new state is computed using the previous state, you can pass a function to setState. 如果使用先前状态计算新状态,则可以将函数传递给setState。 The function will receive the previous value, and return an updated value. 该函数将接收先前的值,并返回更新的值。

So what's wrong with the first option? 那么第一种选择怎么了? Are there some pitfalls? 有一些陷阱吗?

With the particular code in your example, you have the previous value in hand, so there isn't much difference. 对于示例中的特定代码,您手头有先前的值,因此差别不大。 But sometimes you don't. 但是有时候你没有。 For example, suppose you wanted to have a memoized callback function. 例如,假设您想要一个记忆化的回调函数。 Due to the memoization, the value of counter gets locked in when the closure is created, and won't be up to date. 由于使用了备忘录,创建闭包时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>;
}

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

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