反应钩子setState参数

时间:2019-06-16 03:54:27

标签: javascript reactjs react-hooks

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

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

官方文件说:

  

如果新状态是使用先前状态计算的,则可以传递一个   函数为setState。该函数将接收先前的值,   并返回更新的值。

那么第一种选择怎么了?有一些陷阱吗?

1 个答案:

答案 0 :(得分:4)

使用示例中的特定代码,您手头有了先前的值,因此差别不大。但是有时候你没有。例如,假设您想要一个记忆化的回调函数。由于使用了备忘录,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>;
}
相关问题