React useState 钩子,用函数调用 setState

React useState hook, calling setState with function

React 中有一个概念(当使用 hooks 时)让我很困惑。

我做了一个组件来解释(增加一个计数器):

const [counter, setCounter] = useState(0); // counter hook

// code will follow

// render
return (
  <div>
    <button onClick={handleClick}>+</button>
    <h3>{counter}</h3>
  </div>
);

对于处理函数,我看到了设置状态的不同选项。

第一种方法(正常使用setState()):

const handleClick = () => {
  setCounter(counter + 1);
};

第二种方法(在setState()中创建一个函数并返回新值):

const handleClick = () => {
  setCounter((counter) => {
    return counter + 1;
  });
};

我认为不同之处在于,使用第二种方法,您可以在设置状态后立即进行回调,如下所示:

const handleClick = () => {
  setCounter((counter) => {
      return counter + 1;
    }, () => {
      console.log(counter); // trying callback after state is set
  });
};

但是在尝试此操作时(使用这两种方法),控制台显示以下错误消息:

Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().

所以我认为在这两种情况下,使用 useEffect() 作为 setState() 的回调是正确的方法。

我的问题是:这两种方法有什么区别,哪种方法最好设置状态。我已阅读有关状态不变性的内容,但无法立即看出它在此示例中有何不同。

你的情况是一样的。

基本上当你的状态是用你以前的状态计算的时候,你可以使用第二种方法来获取以前的值。

查看关于此的 React 文档:

Functional updates