React Hooks功能更新

时间:2019-12-21 22:53:09

标签: reactjs react-hooks

React的文档(https://reactjs.org/docs/hooks-reference.html#usestate)包含以下示例:

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
    </>
  );
}

为什么以前的代码比以下更好?

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(count - 1)}>-</button>
      <button onClick={() => setCount(count + 1)}>+</button>
    </>
  );
}

1 个答案:

答案 0 :(得分:1)

不是。在您的示例中,另一种方法是完全可以的。但是,还有其他情况,即

(a),如果您有设置状态的效果:

  useEffect(() => {
     // ... do stuff
     setCount(count + 1);
  }, [count]); // whoops, thats kind of recursion. However if we omit it, count might change in the meantime

(b)如果您执行异步操作,并且状态局部变量可能不保存当前状态值:

 (async function action() {
     await /*something*/;
     setCount(count + 1); // is count still up to date?
  })();

在这些情况下,使用setState回调是解决问题的一种方法。