我正在做一个待办事项应用程序。这是违规代码的非常简化的版本。我有一个复选框:
<p><input type="checkbox" name="area" checked={this.state.Pencil} onChange={this.checkPencil}/> Writing Item </p>
这是调用复选框的函数:
checkPencil(){ this.setState({ pencil:!this.state.pencil, }); this.props.updateItem(this.state); }
updateItem是映射为分派到redux的函数
function mapDispatchToProps(dispatch){ return bindActionCreators({ updateItem}, dispatch); }
我的问题是,当我调用updateItem操作并在console.log状态时,它总是落后1步。如果未选中该复选框且该复选框不为true,则仍将状态为true传递给updateItem函数。我是否需要调用另一个函数来强制状态更新?
您应该调用第二个函数作为setState的回调,因为setState异步发生。就像是:
this.setState({pencil:!this.state.pencil}, myFunction)
但是在您的情况下,由于您希望使用参数调用该函数,因此您将不得不变得更有创造力,并且可能创建自己的函数以在道具中调用该函数:
myFunction = () => { this.props.updateItem(this.state) }
将它们结合在一起,它应该可以工作。