在项目中,不知道大家有没有遇到这样的一个问题,比如说有两个页面A,B。A页面中有某个按钮点击后可以跳转到B页面,现在有一个需求就是,我在B页面中做了某些操作,然后点击回退按钮,回到A页面,A页面中的数据也需要刷新过来。嗯,如果是做过android开发的朋友一定会知道,解决这样的需求的方法有很多,比如可以使用activity的生命周期,也可以使用广播等等,但是如果在react native中呢??
我们看一下官网可以知道,react native的生命周期不是针对于页面的,而是组件,什么意思呢?也就是说这个生命周期是组件的生命周期,而不是页面的生命周期,页面在跳转的时候,页面就会回调相应的生命周期的方法,但是组件在页面跳转的时候不一定会回调相应的生命周期方法,所以react native中,使用生命周期这个方式来刷新页面,并不是最好的选择。那么react native中有没有一个类似与广播这样的东东呢。有的,就是这个东西:DeviceEventEmitter.
A页面
import { DeviceEventEmitter } from 'react-native'
//注册这个监听事件
componentDidMount() {
this.subscription = DeviceEventEmitter.addListener('xxxName', (param) => {
//这里的 'param' 可以不写
this.requestData() //调用方法比如:重新请求网络数据
this.setState({
text: param.text
color: param.color
})
})
}
//在组件销毁的时候要将其移除
componentWillUnmount() {
this.subscription.remove();
}
B页面
import { DeviceEventEmitter } from 'react-native'
//页面将要离开的是时候发送通知
componentWillUnmount() {
DeviceEventEmitter.emit('xxxName', {color:'red',text:'通知'});
}
参考作者:
http://www.cnblogs.com/huangjialin/p/6170009.html
https://blog.csdn.net/lq0611/article/details/79695710
https://www.jianshu.com/p/847fbba8bf15
https://blog.csdn.net/j550341130/article/details/81773628
网友评论