React setState 不立即更新 [英] React setState not Updating Immediately
问题描述
我正在开发一个待办事项应用程序.这是违规代码的一个非常简化的版本.我有一个复选框:
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 步.如果复选框未选中且不为真,我仍然会得到传递给 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.
这篇关于React setState 不立即更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!