使用React Navigation将道具从StackNavigator传递到屏幕

时间:2019-07-16 19:40:36

标签: reactjs react-native react-navigation

我正在尝试使用AsyncStorage加载设置,并将一些道具设置到下一个屏幕。我使用sortBy值对数据库结果进行排序。

如果我从App传递带有screenProps的道具,它会导致更多渲染,因为加载sortBy值需要花费时间。由于AuthLoadingScreen决定渲染什么,我想通过将道具直接传递到MainList来减少渲染量

AuthLoadingScreen.js

export default class AuthLoadingScreen extends Component {
    constructor(props) {
      super(props);
      this._bootstrapAsync();
    }

    // Fetch the token from storage then navigate to our appropriate place
    _bootstrapAsync = async () => {
      const userToken = await AsyncStorage.getItem('token');
      const sortValue = await AsyncStorage.getItem('sortBy');
      if (userToken) {

        this.props.navigation.navigate('App',{"sortBy":sortValue}); // I can't send this back to  MainList of AppStack
      } else {
        this.props.navigation.navigate('Onboarding');
      }
    };

    render() {
      return (
        <View>
          <ActivityIndicator />
          <StatusBar barStyle="default" />
        </View>
      );
    }
  }

App.js

export default class App extends Component<Props> {

  render() {
    return (
      <Root>
      <AppContainer/>
      </Root>
    );
  }
}

const AppStack = createStackNavigator(
  {
   MainList: {
      screen: MainListScreen // how to pass props from AppStack to MainListScreen ?
    },
    Settings: {
      screen: Settings,
    }
  },
  {
    initialRouteName:"MainList",
    defaultNavigationOptions: () => ({
      headerStyle: {
        backgroundColor: '#2196f3'
      },
      headerTintColor: 'white'
    })
  }
);

const AppNavigator = createSwitchNavigator(
  {
    AuthLoading: AuthLoadingScreen,
    Onboarding:Onboarding,
    App: AppStack, //logged in users
  },
  {
    initialRouteName: 'AuthLoading',
  }
);



const AppContainer = createAppContainer(AppNavigator);

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

AuthLoadingScreen.js

_bootstrapAsync = async () => {
  const userToken = await AsyncStorage.getItem('token');
  const sortBy = await AsyncStorage.getItem('sortBy');

  if (userToken) {
    this.props.navigation.navigate('App', { sortBy })
  } else {
    this.props.navigation.navigate('Onboarding');
   }
};

然后在MainListScreen文件中访问sortBy,如下所示:

MainListScreen.js

this.props.navigation.state.params.sortBy