react-navigation5.x createBottom

2020-08-14  本文已影响0人  YQSummer

react-navigation 页面第一次加载后 tab切换就不会再刷新了,网上找了很多方法
查到最多的就是一下的方法了,

componentDidMount() {
    this._navListener = this.props.navigation.addListener('didFocus', () => {
      this.getData();
    });
  }

  componentWillUnmount() {
    this._navListener.remove();
  }

我用了之后没有反应,就去官网查了资料5.x后改为了focus和blur

componentDidMount() {
    this._navListener = this.props.navigation.addListener('focus', () => {
      this.getData();
    });
  }

官网代码
React Navigation emits events to screen components that subscribe to them. We can listen to focus and blur events to know when a screen comes into focus or goes out of focus respectively.
例:

function Profile({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      // Screen was focused
      // Do something
    });

    return unsubscribe;
  }, [navigation]);

  return <ProfileContent />;
}

Instead of adding event listeners manually, we can use the useFocusEffect hook to perform side effects. It's like React's useEffect hook, but it ties into the navigation lifecycle.
例:

import { useFocusEffect } from '@react-navigation/native';

function Profile() {
  useFocusEffect(
    React.useCallback(() => {
      // Do something when the screen is focused

      return () => {
        // Do something when the screen is unfocused
        // Useful for cleanup functions
      };
    }, [])
  );

  return <ProfileContent />;
}

参考文献:https://reactnavigation.org/docs/navigation-lifecycle

上一篇下一篇

猜你喜欢

热点阅读