react-navigation 监听页面显隐(viewDidA
2018-03-15 本文已影响427人
wangtieshan
我们经常遇到的需求就是,当某个界面出现的时候,就刷新一下此界面的数据
保证用户的数据处于一种相对同步的情况
在 iOS 中 viewDidAppear 在界面出现的时候总是会执行一次
如此只需要在 viewDidAppear 中加上网络请求即可
react-navigation 中如何实现呢
首先请升级 react-navigation 到最新版本,因为此监听方法是较新版本才更新出来的方法
官网摘抄
willBlur - the screen will be unfocused
willFocus - the screen will focus
didFocus - the screen focused (if there was a transition, the transition completed)
didBlur - the screen unfocused (if there was a transition, the transition completed)
const didBlurSubscription = this.props.navigation.addListener(
'didBlur',
payload => {
console.debug('didBlur', payload);
}
);
// Remove the listener when you are done
didBlurSubscription.remove();
viewDidAppear navigation.addListener didFocus
如下代码:
componentDidMount() {
// 添加监听
this.viewDidAppear = this.props.navigation.addListener(
'didFocus',
(obj)=>{
console.log(obj)
}
)
}
componentWillUnmount() {
// 移除监听
this.viewDidAppear.remove();
}
相信看了如上方法或者官方文档,使用起来是相当简单了
这里略作补充
如上方法添加了监听后
- 导航控制下,此界面出现调用此方法
- 在 tabBar 切换的时候也是能够准确的调用此方法
- 此监听只是监听当前界面的(亲测,放心使用)
所以只要添加了监听,万事大吉