为什么在 React 的 #setState 中使用函数可以解决异步问题? [英] Why does using function inside React's #setState solve async issues?

查看:25
本文介绍了为什么在 React 的 #setState 中使用函数可以解决异步问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

docs,它说React 可能将多个 setState() 调用批处理为单个更新以提高性能",因此它建议对 setState 的参数使用函数而不是对象.这如何解决问题?

From the docs, it says "React may batch multiple setState() calls into a single update for performance" so it recommends using a function instead of an object for setState's argument. How does this solve the problem?

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

推荐答案

当你向 setState 传入一个对象时,react 会接受你传入的任何内容,创建一个事件来跟踪传入的内容,然后最终会更新状态.正如文档所说,如果运行多个 setStates,react 可能会将它们批处理在一起,因为它会异步发生,也就是在未来的某个时刻,当您运行第一个示例时,它可能会使用 this.state.counter 那实际上是旧的并且会导致意想不到的副作用.

When you pass in an object to setState, react will take whatever you pass in, create an event that will track what was passed in, and then will eventually update state. As the docs say, if multiple setStates are run, react may batch those together and since its going to happen asynchronously, aka at some point down the road, when you run the first example it may use a this.state.counter that is actually old and cause unexpected side effects.

第二个选项被认为更安全,因为它很像一个承诺:当你传入一个函数时,React 只会在状态实际更新后才运行这个函数.这确保您每次更新时都有正确的 this.state.counter 变量,使用它们作为回调参数提供的 prevState 变量.

The second option is considered more safe because it is much like a promise: When you pass in a function, React will only run this function once the state has actually been updated. This ensures that you have correct this.state.counter variable each time you update by using the prevState variable they provide as an argument to the callback.

我自己在使用第一种方法时并没有遇到问题,但我也没有尝试过一次充斥一堆 setStates 调用,我确定这确实会出现.我见过这些犯规的人的主要方式是他们在设置状态后立即尝试使用新状态.

I haven't myself ran into an issue using the first method but I also haven't tried flooding a bunch of setStates calls at once which I'm sure is when this does come up. The main way I've seen this foul people up is when they are trying to use the new state right after setting state.

例如:

increaseCounter() {
 this.setState({
   counter: this.state.counter + this.props.increment,
 });

 // this will more then likely be the previous value 
 // as setState does not run right away, but asynchronously 
 this.useNewCounter(this.state.counter) 
}

在那个例子中,人们可能期望当 useNewCounter 被调用时它会使用最新的状态,但它不会,引用仍将指向前一个值,直到 react 更新状态这将在调用此方法后的某个时间点.

in that example one might expect that when useNewCounter is called that it would be using the latest state, but it will not, the reference will still be pointed at the previous value until react updates the state which will be at some point after this method is called.

这篇关于为什么在 React 的 #setState 中使用函数可以解决异步问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆