setState ReactJS中的this.state [英] this.state inside setState ReactJS

查看:26
本文介绍了setState ReactJS中的this.state的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我对ReactJS中setState的异步特性有些困惑.根据React文档,您不应该在setState()中使用this.state.但是,如果我有一个计数器作为状态,并且想要在单击时更新它,就像这样:

  class应用扩展了React.Component {状态= {计数器:0}onClick =()=>{this.setState({counter:this.state.counter + 1})}使成为() {返回 (< div>< div> {this.state.counter}</div>< p onClick = {this.onClick}>点击我</p></div>)}} 

这按预期工作.那么为什么这段代码是错误的呢?

更新:我知道setState是异步的,并且它接受具有以前状态作为参数的回调,但是我不确定为什么要在这里使用它?我想引用setState中的旧状态,所以在这种情况下为什么要使用回调函数?每当执行 this.setState()时,其内部的 this.state 始终会引用旧状态,并且只有在setState具有完成执行,而不是在执行时.

解决方案

您可以在setState调用中访问 prevState :

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

这将使您可以安全地增加当前状态值.

React文档总结了为什么您不能依赖 this.state 在更新期间保持准确: 解决方案

You have access to prevState from within your setState call:

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

这篇关于setState ReactJS中的this.state的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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