美文网首页
React-Native:DeviceEventEmitter和

React-Native:DeviceEventEmitter和

作者: sy随缘 | 来源:发表于2018-09-12 10:43 被阅读0次

参考链接:
React-Native刷新机制-通知【DeviceEventEmitter】
http://www.cnblogs.com/huangjialin/p/6170009.html

React-Native使用【AppState】获取App运行状态(以及监听状态改变事件)
https://www.jianshu.com/p/88fc5cd76386


在项目中,有两个页面A,B。A页面中有某个按钮点击后可以跳转到B页面,现在有一个需求就是,我在B页面中做了某些操作,然后点击回退按钮,回到A页面,A页面中的数据也需要刷新过来。

我们看官网可以知道,react native的生命周期不是针对于页面的,而是组件,什么意思呢?
也就是说这个生命周期是组件的生命周期,而不是页面的生命周期,页面在跳转的时候,页面就会回调相应的生命周期的方法,但是组件在页面跳转的时候不一定会回调相应的生命周期方法,所以react native中,使用生命周期这个方式来刷新页面,并不是最好的选择。

那么react native中有没有一个类似与通知这样的东东呢。
有的,就是这个东西:DeviceEventEmitter.

在页面A中进行注册:

import  {
DeviceEventEmitter
} from 'react-native';

//注册这个监听事件
componentDidMount(){
     DeviceEventEmitter.addListener('xxxName’, Function);
};


//在组件销毁的时候要将其移除
componentWillUnmount(){
    DeviceEventEmitter.remove();
};

在页面B中就可以进行调用了:

import  {
DeviceEventEmitter
} from 'react-native';

 //调用事件通知  param是指传递的相应参数
DeviceEventEmitter.emit('xxxName’,param);

华丽分割线: 具体的示例代码

componentDidMount() {
    // 获取消息是否有未读
    getMessageStatus()
    // 取出保存的版本号和当前版本号比较,如果不同显示指导手册
    // AsyncStorage.getItem('CURRENT_VERSION').then((version) => {
    //   this.setState({ showGuide: DeviceInfo.getVersion() !== version })
    // })
    // 处理被踢下线
    DeviceEventEmitter.addListener('LogDownLine', (logDownMsg) => {
      this.setState({ logDownMsg }, () => {
        // 删除原有 alias
        JzgJPush.deleteAlias()
        JzgJPush.clearAllNotifications()
        setNoRedMessage()
        this.props.actions.signDownShow()
      })
    })
    // 非200状态弹toast
    DeviceEventEmitter.addListener('FetchResponse', (response) => {
      if (response.status !== 200 && response.status !== 700 && response.status !== 725) {
        Toast.show(response.msg || '获取数据失败')
      }
    })

    AppState.addEventListener('change', this.handleAppStateChange)
  }

下面代码顺便说下普通函数和箭头函数的小小区别:
箭头函数:this表示的都是作用范围内的当前对象
普通函数:this表示的调用者对象

举个例子:
A.js文件中调用B.js文件中的方法 functionB,而functionB中有this对象,那么这个this对象表示的就是A中的this对象,而不是B中的this对象。

componentWillUnmount() {
    // DeviceEventEmitter.removeAllListeners()
    AppState.removeEventListener('change', this.handleAppStateChange)
  }

  handleAppStateChange = (appState) => {
    if (appState === 'active') {
      try {
        // 获取消息是否有未读
        getMessageStatus()
        JzgJPush.clearAllNotifications()
      } catch (e) {
        // console.log(e)
      }
    }
  }



相关文章

网友评论

      本文标题:React-Native:DeviceEventEmitter和

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