简体   繁体   English

setState ReactJS 中的 this.state

[英]this.state inside setState ReactJS

So I have some confusion regarding the async nature of setState in ReactJS.所以我对 ReactJS 中 setState 的异步性质有些困惑。 As per React docs, you shouldn't use this.state inside setState().根据 React 文档,您不应在 setState() 中使用 this.state。 But if I have a counter as a state and i want to update it on click like this:但是,如果我有一个计数器作为状态,并且我想在单击时更新它,如下所示:

class App extends React.Component {
    state = { counter: 0 }

    onClick = () => {
        this.setState({counter: this.state.counter + 1})
    }

    render() {
        return (
          <div>
            <div>{this.state.counter}</div>
            <p onClick={this.onClick}>Click me</p>
          </div>
        )
    }
}

This works as expected.这按预期工作。 So why is this code wrong?那么为什么这段代码是错误的呢?

UPDATE: I know that setState is async, and it accepts a callback which has previous state as an argument, but I am not sure why I should use it here?更新:我知道 setState 是异步的,它接受一个以先前状态作为参数的回调,但我不确定为什么要在这里使用它? I want to refer to the old state inside setState, so why should I use the callback function in this case?我想引用setState里面的旧状态,那么为什么要在这种情况下使用回调函数呢? Whenever this.setState() is executed, this.state inside it will always refer to the old state, and its value will be changed to the new state only after setState has finished executing, not while it is executing.每当this.setState()被执行时, this.state里面的this.state总是指向旧状态,并且只有在 setState 执行完后,它的值才会改变为新状态,而不是在它正在执行的时候。

You have access to prevState from within your setState call:您可以在 setState 调用中访问prevState

this.setState((prevState) => ({
    counter: prevState.counter +1
}))

That will allow you to safely increment the current state value.这将允许您安全地增加当前状态值。

The React documentation summarises why you cannot rely on this.state to be accurate during update: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous React 文档总结了为什么你不能依赖this.state在更新期间是准确的: https : this.state

setState accepts a function as a parameter with previous state as argument. setState接受一个函数作为参数,以前的状态作为参数。 Refacto as follows to avoid competition problems:重构如下以避免竞争问题:

onClick = () => {
    this.setState(prevState => ({counter: prevState.counter + 1}))
}

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

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