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

前端 未结 5 1283
无人共我
无人共我 2020-12-07 22:44

Perviously when I wanted to make some actions when screen is opened I put them inside componentDidMount. For example I can fetch some data.

like this.

相关标签:
5条回答
  • 2020-12-07 23:27

    NavigationEvents is another way to add event listener just inside JSX. See documentation for details.

    It looks something like this:

    import { NavigationEvents } from 'react-navigation';
    
    return (
      <ScrollView style={styles.container}>
        <NavigationEvents            
          onDidBlur={payload => console.log('did blur', payload)}
        />
        {this.props.children}
      </ScrollView>
    );
    
    0 讨论(0)
  • 2020-12-07 23:30

    With react-navigation, you can do that in 2 steps:

    1. Add listeners in componentDidMountor componentWillMount, to hook events

    2. Remove listeners in componentWillUnmount, to avoid unexpected calling

    API Reference Documents v3.x, v4.x, v5.x :

    React-navigation v3.x, v4.x:

    addListener - Subscribe to updates to navigation lifecycle

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

    • willFocus - the screen will focus
    • didFocus - the screen focused (if there was a transition, the transition completed)
    • willBlur - the screen will be unfocused
    • didBlur - the screen unfocused (if there was a transition, the transition completed)

    React-navigation 3.x, 4.x example:

    const didBlurSubscription = this.props.navigation.addListener(
      'didBlur',
      payload => {
        console.debug('didBlur', payload);
      }
    );
    
    // Remove the listener when you are done
    didBlurSubscription.remove();
    

    Ref v4.x https://reactnavigation.org/docs/4.x/navigation-prop/#addlistener---subscribe-to-updates-to-navigation-lifecycle

    UPDATED v5.x

    The events had been changed in v5.x

    Screens can add listeners on the navigation prop like in React Navigation. By default, there are 2 events available:

    • focus - This event is emitted when the screen comes into focus
    • blur - This event is emitted when the screen goes out of focus
    • state (advanced) - This event is emitted when the navigator's state changes

    Sample code from reactnavigation.org

    class Profile extends React.Component {
      componentDidMount() {
        this._unsubscribe = navigation.addListener('focus', () => {
          // do something
        });
      }
    
      componentWillUnmount() {
        this._unsubscribe();
      }
    
      render() {
        // Content of the component
      }
    }
    

    Ref v5.x: https://reactnavigation.org/docs/navigation-events

    0 讨论(0)
  • 2020-12-07 23:32

    FOR V3.x and V4.x 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);
    

    FOR V5.x Please use this.

     componentDidMount(){
        const { navigation } = this.props;
        this.focusListener = navigation.addListener("focus", () => {      
        // Call ur function here.. or add logic.     
        });
    }
    
    0 讨论(0)
  • 2020-12-07 23:32

    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

    0 讨论(0)
  • 2020-12-07 23:38

    The latest version of react-navigation provides custom hooks that let you react to focus and blur events: https://reactnavigation.org/docs/function-after-focusing-screen.

    The following is an example from their docs that uses the onFocusEffect hook to make an API call on focus (it cleans up the effect when the screen goes out of focus):

    import { useFocusEffect } from '@react-navigation/native';
    
    function Profile({ userId }) {
      const [user, setUser] = React.useState(null);
    
      useFocusEffect(
        React.useCallback(() => {
          const unsubscribe = API.subscribe(userId, user => setUser(data));
    
          return () => unsubscribe();
        }, [userId])
      );
    
      return <ProfileContent user={user} />;
    }
    
    0 讨论(0)
提交回复
热议问题