react-native componentDidMount / componentWillReceiveProps

componentWillReceiveProps 周期函数调用 this.state.start 发现总是慢一步





父组件引入了三个子组件。当父组件的日期改变时,更改 state 里面的 start_time end_time, 此时子组件需要接收父组件传过来的日期值,并重新调用接口获取新数据。
如,现在是设备报警,当父组件日期更改时,会触发子组件 componentWillReceiveProps 这个生命周期函数;而切换到发动机报警的时候,触发的是engine组件的 componentDidMount 这个生命周期函数。

父组件传过来的值,在componentWillReceiveProps(nextProps) 周期函数中可以接收并设置 setState({start_time: nextProps.start}),但是,在后面的函数中不要直接调用 this.state.start_time . ----查看函数生命周期,此时设置了setState,但是需要在等几个生命周期函数后才能被设置。-----因而在componentWillReceiveProps 调用 this.state.start_time.会发现,这个日期总比现在传过来的参数晚一次。 在componentWillReceiveProps 中函数就调用nextProps.start这个参数就可以。

原文地址:https://www.cnblogs.com/xk-g/p/9597823.html