反应setState不立即更新 [英] React setState not Updating Immediately

查看:360
本文介绍了反应setState不立即更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究待办事项.这是违规代码的非常简化的版本.我有一个复选框:

I'm working on a todo application. This is a very simplified version of the offending code. I have a checkbox:

 <p><input type="checkbox"  name="area" checked={this.state.Pencil}   onChange={this.checkPencil}/> Writing Item </p>

以下是调用该复选框的函数:

Here's the function that calls the checkbox:

checkPencil(){
   this.setState({
      pencil:!this.state.pencil,
  }); 
  this.props.updateItem(this.state);
}

updateItem是一个映射为分派到redux的函数

updateItem is a function that's mapped to dispatch to redux

function mapDispatchToProps(dispatch){
  return bindActionCreators({ updateItem}, dispatch);
}

我的问题是,当我调用updateItem操作并在console.log状态时,它总是落后1步.如果未选中该复选框且该复选框不为true,则仍将状态为true传递给updateItem函数.我需要调用另一个函数来强制状态更新吗?

My problem is that when I call the updateItem action and console.log the state, it is always 1 step behind. If the checkbox is unchecked and not true, I still get the state of true being passed to the updateItem function. Do I need to call another function to force the state to update?

推荐答案

由于setState异步发生,因此您应调用第二个函数作为setState的回调.像这样:

You should invoke your second function as a callback to setState, as setState happens asynchronously. Something like:

this.setState({pencil:!this.state.pencil}, myFunction)

但是在您的情况下,由于您希望使用参数来调用该函数,因此您将不得不变得更有创造力,并且可能创建自己的函数以在道具中调用该函数:

However in your case since you want that function called with a parameter you're going to have to get a bit more creative, and perhaps create your own function that calls the function in the props:

myFunction = () => {
  this.props.updateItem(this.state)
}

将它们组合在一起,它应该可以工作.

Combine those together and it should work.

这篇关于反应setState不立即更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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