【问题标题】:Why route.params is giving me undefined inside the component when using react navigation in react native?在 react native 中使用反应导航时,为什么 route.params 在组件内部给我未定义?
【发布时间】:2021-06-11 05:03:16
【问题描述】:

请不要将此问题标记为重复。其他答案并没有保存这个。

我现在正在尝试获取 react native 组件中的 route.params 并将其呈现在屏幕上

我现在正在尝试吃零食。

问题是当我在组件的开头 console.log route.params console.log 向我显示参数时。

但是当我 console.log route.params.mathNumber console.log 显示我 undefined

这是图片

既然我确定我传递了正确的参数mathNumber,这里的问题是什么?

这是我正在使用的代码

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() =>
          navigation.navigate('Details', {
            params: {
              mathNumber: Math.floor(Math.random() * 999),
            },
          })
        }
      />
    </View>
  );
}

function DetailsScreen({ navigation, route }) {
  const { mathNumber } = route.params;
  console.log(route.params)
  console.log(route.params.mathNumber);
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen {mathNumber} here</Text>
      <Button
        title="Go to Details... again"
        onPress={() =>
          navigation.push('Details', {
            params: {
              mathNumber: Math.floor(Math.random() * 999),
            },
          })
        }
      />
    </View>
  );
}

对于ez测试用例 你可以去这个小吃链接

Link To Snack

并用我的代码替换 2 组件

如您所见,当我浏览不同的详细信息屏幕时,我正在尝试渲染不同的 mathNumber

【问题讨论】:

    标签: reactjs react-native react-navigation


    【解决方案1】:

    你添加参数的方式你会得到这样的 mathNumber

    const  mathNumber  = route.params?.params.mathNumber;
    

    或者你可以这样做

     onPress={() =>
              navigation.navigate('Details', {
                  mathNumber: Math.floor(Math.random() * 999),
              })
            }
    

    【讨论】:

      猜你喜欢
      • 2021-06-18
      • 2022-01-21
      • 1970-01-01
      • 2020-11-14
      • 2016-07-28
      • 2015-06-02
      • 1970-01-01
      • 2021-06-07
      • 2017-03-27
      相关资源
      最近更新 更多