React Native页面间传值问题:item未定义报错
解决React Native导航中“item未定义”的问题
问题场景
点击食谱卡片跳转至详情页时,出现「item未定义」的错误,无法正常展示食谱详情内容。
错误原因分析
- 组件参数接收错误:
RecipeDetails组件错误地将navigation和route作为独立参数接收,实际上React Native组件的props是一个包含这两个属性的对象。 - 导航参数传递格式错误:
RecipeCard中使用navigation.navigate时,错误嵌套了screen字段,导致参数无法正确传递。 - 组件标签大小写错误:
RecipeDetails中使用了小写的<image>标签,React Native组件必须大写开头。
修复方案
1. 修正RecipeCard的导航参数传递
修改Pressable的onPress跳转逻辑,移除多余的screen嵌套,直接传递参数:
// RecipeCard组件中Pressable的onPress修改为 onPress={() => navigation.navigate("RecipeDetails", { item: item, }) }
2. 修正RecipeDetails的参数接收与组件标签
- 正确解构组件props获取
navigation和route - 将
<image>改为大写的<Image>(需导入Image组件) - 增加参数空值校验,避免异常报错
修复后的RecipeDetails代码:
import { Pressable, StyleSheet, Text, View, Image } from "react-native"; // 新增Image导入 import React from "react"; import Header from "../components/Header"; import { SafeAreaView } from "react-native-safe-area-context"; const RecipeDetails = ({ navigation, route }) => { // 解构props对象 const { item } = route.params || {}; // 增加空值校验 if (!item) { return ( <SafeAreaView> <Header /> <Text>未找到食谱信息</Text> <Pressable onPress={() => navigation.goBack()}> <Text>返回</Text> </Pressable> </SafeAreaView> ); } return ( <SafeAreaView> <Header /> <Text>Hello I am the details screen</Text> <Pressable onPress={() => navigation.goBack()}> <Text>返回</Text> </Pressable> <View> <Image source={item.image} style={{ width: 200, height: 200 }} /> {/* 修正标签并添加基础样式 */} <Text>{item.name}</Text> </View> </SafeAreaView> ); }; export default RecipeDetails; const styles = StyleSheet.create({});
额外优化建议
- 在
RecipeCard的FlatList中添加keyExtractor属性,提升列表渲染性能:
<FlatList data={recipeList} keyExtractor={(item) => item.id} // 假设每个食谱对象包含唯一id字段 // ...其他原有属性 />
内容的提问来源于stack exchange,提问作者Jess
相关产品推荐
相关产品推荐

