![](/img/trans.png)
[英]react-native : state not updated inside the componentWillReciveProps
[英]react-native How to listen to updated mobx state
在我的本机反应项目中,当我单击一个按钮时,我的mobx应用程序状态会更新。
我想使用反应lifecycle method
来侦听此更新并自动对其进行更新。 所以我正在使用componentDidUpdate
。
componentDidUpdate(nextProps, nextState) {
this.setState({number:store.requestObject.number},
console.log(this.state.number), 'state changed')
}
但似乎此方法不会自动更新。
我应该使用其他生命周期方法吗? 任何意见或建议将非常有帮助。 提前致谢!
编辑
在我的第一个屏幕中,我有一个按钮,然后单击onPress
可以将数据存储到mobx
store
。 然后,在第二个屏幕中,我想调用mobx
state
并用当前组件的状态对其进行更新。 我可以使用类似这样的按钮:
<Button onPress={()=> this.setState({currentState:store.mobxState})}>
然后,我当前的component state
将与运行良好的mobx state
匹配,但我想自动执行此操作(不使用按钮)。
您不会在下一行获得更改的状态值。 我们可以在这里使用回调方法
handleMonthChange_next = () => {
this.setState({
currentMonth: this.state.currentMonth + 1
}, () => {
this.props.getCalendarData(this.state.currentMonth)
})}
您可以使用getDerivedStateFromProps
static getDerivedStateFromProps(props, state){
}
请注意,无论原因如何,都会在每个渲染器上触发此方法。 这与UNSAFE_componentWillReceiveProps相反,后者仅在父级导致重新渲染时才触发,而不是由于本地setState触发。
更具体地说,当您调用this.setState({})
,将调用您的getDerivedStateFromProps
,从那里您可以读取更改后的状态值并执行一些操作。
如果您不想使用用户给定的方法,请创建自定义事件以监听状态
stateListiner = (state) =>{
this.setState(state,()=>{
//listen to state change after setting it
// add your logic after state update
})
}
// call the state
let givenState = {name:'xyz',visible:false,}
this.stateListiner(givenState) // this will set your state and fire the callback function
使用react setState
回调 :
componentDidUpdate(prevProps, prevState) {
this.setState(
{ number: store.requestObject.number },
() => console.log(this.state.number, 'state changed') // callback will fire after state update
);
}
请注意,尽管建议将componentDidUpdate
中的设置状态置于条件检查之后,以免使您的代码陷入无限循环。 上面的代码将。 同样,它接收的参数是前一个状态和属性,而不是下一个。 仅在状态更新或组件接收到新的prop值后才调用它。
componentDidUpdate(prevProps, prevState) {
if (prevProps.value !== this.props.value) {
// handle change, log it, api call, call other callback, etc...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.