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

前端 未结 5 1294
无人共我
无人共我 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: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 ;
    }
    

提交回复
热议问题