You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native页面传参报错:TypeError: undefined is not an object

React Navigation 路由参数获取报错:TypeError: undefined is not an object (evaluating 'route.params.item')

问题原因分析

这个报错本质是route.params为undefined,导致无法解构出item。常见触发场景:

  • 跳转时目标路由名称与导航栈配置的名称不匹配,参数未正常传递
  • 直接进入ReviewsScreen(比如深链接、页面刷新),无参数传入
  • 参数传递过程中意外丢失

解决方法

1. 核对路由名称与导航配置一致性

检查导航栈注册代码,确保ReviewsScreen对应的路由名称和navigate调用的第一个参数完全一致:

// 导航栈配置示例
<Stack.Navigator>
  <Stack.Screen name="Home" component={HomeScreen} />
  <Stack.Screen name="Reviews" component={ReviewsScreen} /> {/* 名称必须和navigate的第一个参数匹配 */}
</Stack.Navigator>

2. 添加参数安全解构逻辑

避免直接访问route.params.item,先判断参数是否存在,防止报错:

const ReviewsScreen = ({ navigation, route}) => {
  // 方式1:用可选链+默认空对象
  const item = route.params?.item || {};

  // 方式2:解构时给参数和item都加默认值
  const { item = {} } = route.params || {};

  return (
    <View style={styles.container}>
      <StatusBar style="auto" />
      <Text style={styles.homeText}>{item.title || '无标题'}</Text>
      <Text style={styles.homeText}>{item.body || '无内容'}</Text>
      <Text style={styles.homeText}>{item.rating || '0'}</Text>
      <View style={styles.button}>
        <Button title='home' color={'coral'} onPress={() => navigation.goBack()}/>
      </View>
    </View>
  );
};

3. 明确传递所需字段(更贴合你的需求)

如果你只需要title、rating、body三个字段,可以直接传递这些字段,减少冗余:

// HomeScreen 中修改跳转逻辑
<TouchableOpacity onPress={() => navigation.navigate('Reviews', {
  title: item.title,
  rating: item.rating,
  body: item.body
})}>
  <Text style={styles.homeText}>{item.title}</Text>
</TouchableOpacity>

// ReviewsScreen 中直接解构所需字段
const ReviewsScreen = ({ navigation, route}) => {
  const { title = '无标题', rating = '0', body = '无内容' } = route.params || {};

  return (
    <View style={styles.container}>
      <StatusBar style="auto" />
      <Text style={styles.homeText}>{title}</Text>
      <Text style={styles.homeText}>{body}</Text>
      <Text style={styles.homeText}>{rating}</Text>
      <View style={styles.button}>
        <Button title='home' color={'coral'} onPress={() => navigation.goBack()}/>
      </View>
    </View>
  );
};

4. 错误用法说明

你尝试的<HomeScreen navigation={navigation} route={route}/>是错误的,这是直接在ReviewsScreen中渲染HomeScreen组件,并非传递参数,会导致首页内容被带入评论页,直接舍弃即可。

内容的提问来源于stack exchange,提问作者Gun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 09:09:16