react navigation 导航自带返回按钮的返回刷新功能

我们假设B页面返回到A页面。

方法一

在A页面中设置监听器 :

componentDidMount(){
  this.backFromShopListener = DeviceEventEmitter.addListener(
    'BackRefresh',  //监听器名
    () => {
      this.getDeviceList(); //此处写你的得到列表数据的函数
    },
  );
}

componentWillUnmount() {
    this.backFromShopListener && this.backFromShopListener.remove();
}

在B页面中发送通知:

import { DeviceEventEmitter} from 'react-native';
// 页面销毁时发送通知
componentWillUnmount() {
  DeviceEventEmitter.emit('BackRefresh', {});
}

方法二

来源:https://www.jianshu.com/p/f584c0c406e3

封装监听组件PageListen

import React, {Component} from 'react';
import {useFocusEffect} from '@react-navigation/native';
//监听页面返回 刷新数据
const PageListen = ({onUpdate}) => {
  useFocusEffect(
    React.useCallback(() => {
      onUpdate();
      return () => {
        // Do something when the screen is unfocused
      };
    }, [onUpdate]),
  );

  return null;
};

export default PageListen;

渲染出来

<PageListen onUpdate={this._onUpdate} />
_onUpdate() {
  console.log('返回时刷新页面');
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容