React Native不通过导航参数传递数据

时间:2020-03-10 15:05:55

标签: javascript react-native react-navigation

我试图导航到另一个屏幕时传递一些数据,但是它不起作用。它导航到屏幕,但数据未定义。

我在“产品”屏幕上有此按钮:

onPress={() => {
  props.navigation.navigate("Login", {
    test: "This is just a test"
  });
}}

登录屏幕:

const LoginScreen = props => {    
  const test = props.navigation.getParam("test");
  console.log(test);

测试未定义。

我的导航器(我从此代码段中删除了导入和其他内容):

const MainNavigator = createStackNavigator(
  {
    Home: HomeScreen,
    Produto: ProdutoScreen,
  },
  {
    initialRouteName: "Home"
  }
);

const LoginNavigator = createStackNavigator(
  {
    Login: LoginScreen
  }
);

const DrawerNavigator = createDrawerNavigator(
  {
    Main: {
      screen: MainNavigator
    },
    Login: {
      screen: LoginNavigator
    }
  }
);

const SwitchNavigator = createSwitchNavigator({
  Start: StartScreen,
  Home: DrawerNavigator
});

2 个答案:

答案 0 :(得分:0)

只需更新您尝试访问该参数的行即可。像这样

const LoginScreen = props => {    
  const test = props.navigation.state.params.test;
  console.log(test);
}

答案 1 :(得分:0)

只需执行

const MainNavigator = createStackNavigator(
  {
    Home: HomeScreen,
    Produto: ProdutoScreen,
    Login: LoginScreen,     //this will resolve your issue
  },
  {
    initialRouteName: "Home"
  }
);