简体   繁体   English

反应 useState 钩子,用 function 调用 setState

[英]React useState hook, calling setState with function

There is a concept in React (when using hooks) that confuses me. React 中有一个概念(当使用钩子时)让我感到困惑。

I made a component for explanation (that increases a counter):我制作了一个组件进行解释(增加了一个计数器):

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

// code will follow

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

For the handler function, I have seen different options to set the state.对于处理程序 function,我看到了设置 state 的不同选项。

First method (using setState() normally):第一种方法(通常使用setState() ):

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

Second method (creating a function inside setState() and returning the new value):第二种方法(在setState()中创建 function 并返回新值):

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

I thought the difference would be that with the second method, you could immediately do a callback after setting the state, like this:我认为不同之处在于,使用第二种方法,您可以在设置 state 后立即进行回调,如下所示:

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

But when trying this (with both methods), the console displays the following error message:但是在尝试这个(使用两种方法)时,控制台会显示以下错误消息:

Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument.警告:State 更新来自 useState() 和 useReducer() Hooks 不支持第二个回调参数。 To execute a side effect after rendering, declare it in the component body with useEffect().要在渲染后执行副作用,请在组件主体中使用 useEffect() 声明它。

So I think in both cases, using useEffect() as a callback on setState() is the right way.所以我认为在这两种情况下,使用useEffect()作为setState()的回调是正确的方法。

My question is: what is the difference between the two methods and what method is best to set the state.我的问题是:这两种方法有什么区别,什么方法最好设置state。 I have read about state immutability but can not immediately see how it would make a difference in this example.我已阅读有关 state 不变性的信息,但无法立即看到它在此示例中有何不同。

In your case it's the same.在你的情况下是一样的。

Basically when your state is computed with your previous state you can use the second approach which gets the previous value.基本上,当您使用之前的 state 计算您的 state 时,您可以使用第二种方法来获取之前的值。

Have a look in React docs about this:查看 React 文档中的相关内容:

Functional updates 功能更新

Since this question is gaining some attention I will add this example.由于这个问题引起了一些关注,我将添加这个示例。

<button onClick={() => setCount(0)}>Reset</button>
<button onClick={() => setCount((prevCount) => prevCount - 1)}>-</button>
<button onClick={() => setCount((prevCount) => prevCount + 1)}>+</button>

You can see that for + and - the functional setState is being used, this is because the new state value is computed using the previous state (you are adding/subtracting from the previous count value).您可以看到对于+-正在使用功能setState ,这是因为新的 state 值是使用先前的 state 计算的(您正在从先前的计数值中添加/减去)。

The reset button is using the normal form, because it doesn't compute the new state value based on a computation on the old value, it always just sets it to a fixed number (for example 0 ). reset按钮使用正常形式,因为它不会根据旧值的计算计算新的 state 值,它总是将其设置为固定数字(例如0 )。

So in my case, the best thing to do would have been using the functional setState .因此,就我而言,最好的办法是使用功能setState

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

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