美文网首页ReactNative
react-navigation 监听页面显隐(viewDidA

react-navigation 监听页面显隐(viewDidA

作者: wangtieshan | 来源:发表于2018-03-15 09:51 被阅读427次

    我们经常遇到的需求就是,当某个界面出现的时候,就刷新一下此界面的数据
    保证用户的数据处于一种相对同步的情况

    在 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();
        }
    

    相信看了如上方法或者官方文档,使用起来是相当简单了

    这里略作补充

    如上方法添加了监听后

    1. 导航控制下,此界面出现调用此方法
    2. 在 tabBar 切换的时候也是能够准确的调用此方法
    3. 此监听只是监听当前界面的(亲测,放心使用)

    所以只要添加了监听,万事大吉

    欢迎加入QQ群: 722600238

    在这里可以讨论、帮助你解决你遇到的问题

    相关文章

      网友评论

        本文标题:react-navigation 监听页面显隐(viewDidA

        本文链接:https://www.haomeiwen.com/subject/iezqqftx.html