React Native的route.params未定义。

3
我尝试使用 navigation.navigate('Merchant', store ) 将数据从 home.js 屏幕传递到 merchant.js 屏幕,但当我尝试实际使用 route.params 时,它返回 undefined。
这是我的 home.js:
export default function Home( { navigation }) {
...
{storeData.map(store => {
    return (
     <View>
      <TouchableOpacity>
        <Text style={styles.categoryName}
          onPress={() => {navigation.navigate('Merchant', store)}}>
         {store.name}
        </Text>
      </TouchableOpacity>

Merchant.js

function Merchant({ navigation, route }) {
    console.log(route);
...
}

输出:

{"key": "Merchant-86K9u5ytF32VGMRcO9s2g", "name": "Merchant", "params": undefined}

我不知道发生了什么。我试过使用 navigation.push() 和 navigate('Merchant', {name: store.name}),但仍然得到 undefined。

如果您想粘贴更多与我的堆栈导航相关的代码,我可以查看。


https://reactnavigation.org/docs/params/ 上说:“通过将参数放入对象中作为第二个参数来将参数传递给路由”。你尝试过使用花括号 => {store} 而不是 store 来传递 store 吗? - Elson Ramos
也许你的“store”未定义,你可以使用console.log来确保吗? - whygee
是的,我已经尝试使用花括号了,而且是的,store不是未定义的。 - Travis Sherman
兄弟,这个应该肯定能工作,你能提供一个展示小吃吗?这样我们就可以研究一下了。另外,请告诉我storeData中的数据类型是什么?(字符串?字符串数组?对象数组......) - Daniyal Shaikh
嘿,我已经创建了我的小吃,但现在出现了错误。这是链接 https://snack.expo.dev/B0Dztrfqt - Travis Sherman
显示剩余3条评论
2个回答

0

你试过这个吗?

navigation.navigate('Merchant', store)

通过以下方式访问值:

navigation.getParam('onePropertyOfStoreHere');

当我尝试这样做时,它显示导航.getParam不是一个函数。 - Travis Sherman
你正在使用什么导航库?是从@react-navigation/native导入的吗?你使用的是哪个版本? - Akza
我使用的是"@react-navigation/native": "^6.0.1"。 - Travis Sherman
很奇怪,根据文档 https://reactnavigation.org/docs/params/,你所做的是正确的。也许如果你能创建一个可重现的 Snack 代表你的代码,将有助于我们追踪问题。 - Akza

0

好的,我明白为什么它是未定义的了。因为我有另一个堆栈,它以Merchant.js为顶部开始。

<Stack.Navigator initialRouteName="Merchant" headerShown='false'>
    <Stack.Screen name="Merchant" component={Merchant} />
    <Stack.Screen name="ProductInfo" component={ProductInfo}/>
</Stack.Navigator>

这一定让应用程序感到困惑,因为我正在从主屏幕移动到商家屏幕,但它进入了另一个堆栈。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接