【问题标题】:Can i know about any pending state transition in react before performing an operation?在执行操作之前,我可以知道反应中的任何未决状态转换吗?
【发布时间】:2017-05-10 18:37:26
【问题描述】:
我必须在我的代码中执行一个操作。此操作涉及从我的状态中获取值。在某些情况下,我的状态返回旧值。是否有任何功能可以帮助我在所有挂起的状态转换完成后触发我的代码?
save : function(){
//here am using state and it doesnt reflect new value
saveFunc(this.state.type);
}
【问题讨论】:
标签:
javascript
reactjs
javascript-framework
【解决方案1】:
你应该使用shouldComponentUpdate()
shouldComponentUpdate() 在接收新道具或状态时在渲染之前调用。默认为 true 初始渲染或使用 forceUpdate() 时不调用此方法。
read more here
所以你可以做的是:
shouldComponentUpdate(nextProps, nextState) {
if(this.state.type !== nextState.type) {
// Do what you want
}
}
希望对你有帮助。