React Navigation - How to pass data across different screens in TabNavigator?

后端 未结 5 1951
野的像风
野的像风 2021-01-14 06:17

I have a TabNavigator, and in each tab is a StackNavigator. Inside the StackNavigator, I have screens. The screens in each Tab do not call each other directly; the TabNaviga

5条回答
  •  爱一瞬间的悲伤
    2021-01-14 06:48

    @tempomax tried same with AsyncStorage but data came in with a delay. Sometimes you don't need Redux if your app stays small.

    So tried to find a way without Redux. Here is what I came up with

    I hope it's not too late to answer. Solved it with NavigationEvents and setting params to Route.

    The problem with tab is that you can´t pass params to screen because navigation.navigate will be triggered automatically if createMaterialTopTabNavigator is swiped or clicked on non-active TabBar Button.

    This can be solved with NavigationEvent like follow.

        import React from 'react';
        import { View } from 'react-native';
        import { NavigationEvents } from 'react-navigation';
    
        const MyScreen = () => (
          
             console.log('will focus',payload)}
              onDidFocus={payload => console.log('did focus',payload)}
              onWillBlur={payload => 
                 /*
                  if screen is about to change this will be triggred
                  In screen 'MyScreen2' you can get it with navigation.params
                 */
                  this.props.navigation.navigate('MyScreen2', { name: 'Brent' })
              }
              onDidBlur={payload => console.log('did blur',payload)}
            />
            {/* 
              Your view code
            */}
          
        );
    
        export default MyScreen;
    

    Now you can get the data in MyScreen2

     /* 2. Get the param, provide a fallback value if not available */
    const { navigation } = this.props;
    const itemId = navigation.getParam('name', 'DefaultName');
    const otherParam = navigation.getParam('otherParam', 'some default value');
    

提交回复
热议问题