react-navigation: Detect when screen, tabbar is activated / appear / focus / blur

血红的双手。 提交于 2019-11-29 01:08:50

With react-navigation, you can do that.

  1. Add listeners in componentDidMountor componentWillMount

    this.subs = [
      this.props.navigation.addListener('didFocus', (payload) => this.componentDidFocus(payload)),
    ]; 
    

    or

    this.subs = [
      this.props.navigation.addListener('didFocus', this.componentDidFocus),
      this.props.navigation.addListener('willBlur', this.componentWillBlur),
    ];
    

    Then you can do anything in componentDidFocus, like fetching data, updating data,...

  2. In componentWillUnmount, remove listeners

    componentWillUnmount() {
      this.subs.forEach(sub => sub.remove());
    }
    

For more detail, see this PR: https://github.com/react-navigation/react-navigation/pull/3345

Updated 3.x:

addListener - Subscribe to updates to navigation lifecycle

React Navigation emits events to screen components that subscribe to them:

  • 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)

Ref: https://reactnavigation.org/docs/en/navigation-prop.html#addlistener-subscribe-to-updates-to-navigation-lifecycle

Updated 3.x example:

const didBlurSubscription = this.props.navigation.addListener(
  'didBlur',
  payload => {
    console.debug('didBlur', payload);
  }
);

// Remove the listener when you are done
didBlurSubscription.remove();

JSON payload:

{
  action: { type: 'Navigation/COMPLETE_TRANSITION', key: 'StackRouterRoot' },
  context: 'id-1518521010538-2:Navigation/COMPLETE_TRANSITION_Root',
  lastState: undefined,
  state: undefined,
  type: 'didBlur',
};

componentDidMount / componentWillUnmount does not work in all cases of navigation (like tabs).

You need to use addListener with events didFocus and didBlur to make such actions. See documentation for details

Armar

This might be late but this is how I solved it. See the code below. Don't forget to import withNavigation and wrap your export default withNavigation.

import { withNavigation } from "react-navigation";
 componentDidMount() {
    const { navigation } = this.props;
    this.focusListener = navigation.addListener("didFocus", () => {
      // The screen is focused
      // Call any action
    });
  }

  componentWillUnmount() {
    // Remove the event listener
    this.focusListener.remove();
  }

export default withNavigation(Your Class Name);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!