在下面的代码中,我获得了year的当前状态,当您按下主组件中的按钮时,状态会发生变化:
componentWillReceiveProps(nextProps){
this.setState({
update: true
});
if(nextProps.year===2019){
console.log('oneeeeeee',this.state.update)
this.setState({
dates: ['09.2018', '10.2018', '11.2018', '12.2018'],
numbers: ['3000', '4000', '3300', '2700'],
},() => {
this.setState({update: false})
});
}
}问题是,我使用的计划捕捉菜单本身的每一个按钮单击,并在单击它时重新绘制计划。
如果删除update属性,一切都会正常工作。每次更改year时,我都会将一个update分配给true,并向它传输新的数据。在那之后,我想转到update: false
请告诉我,只有在我将数据转移到false和numbers之后,如何才能将update传输到dates
我试着使用回调,但它不起作用。谢谢你的任何建议!
发布于 2019-02-21 13:40:46
有几件事你需要纠正。
第一:首先,setState是异步和批处理的,因此为update: true调用setState,并将立即更新状态。
第二:在执行任何在nextProps中的操作之前,必须始终比较当前和componentWillReceiveProps中的
第三:从版本16.3.0开始就不再推荐componentWillReceiveProps了,因此我重新注释您使用componentDidUpdate代替
使用componentWillReceiveProps的示例
componentWillReceiveProps(nextProps){
if (nextProps.year !== this.props.year && nextProps.year === 2019) {
this.setState({
update: true
}, () => {
this.setState({
dates: ['09.2018', '10.2018', '11.2018', '12.2018'],
numbers: ['3000', '4000', '3300', '2700'],
},() => {
this.setState({update: false})
});
})
}
}https://stackoverflow.com/questions/54808352
复制相似问题