简体   繁体   English

这是根据之前的 state 更新 state 的正确方法吗?

[英]Is this the correct way to update a state based on the previous state in react?

Here's my code:这是我的代码:

  const [val, setVal] = useState(0);

  function onClick() {
    setVal(val + 1);
  }

I just wanted to check if this is the correct way to update a state based on a previous state?我只是想检查这是否是根据以前的 state 更新 state 的正确方法? Why/why not?为什么/为什么不?

This is a perfectly fine approach.这是一个非常好的方法。 Note that you could also get the value of your current state as a callback parameter on setVal , eg: setVal(prevState => prevState + 1) .请注意,您还可以获取当前 state 的值作为setVal上的回调参数,例如: setVal(prevState => prevState + 1)

Just be careful when manipulating arrays or objects since they shouldn't be directly mutated (with methods such as push or pop etc).操作 arrays 或对象时要小心,因为它们不应该直接变异(使用pushpop等方法)。

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

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