React Navigation页面间传递Props异常问题排查
问题排查与修复方案
1. 正确解构导航参数(核心问题)
你的RecipeScreen未正确从route.params中解构item,导致多处使用item时触发未定义错误,同时掩盖了category参数的实际传递情况。修改参数获取逻辑:
export default function RecipeScreen(props) { const { navigation, route } = props; // 用空对象兜底,避免无参数时解构报错 const { item, category, title } = route.params || {}; // 后续代码可正常使用item、category、title // ... }
2. 添加参数空值保护
即使参数传递正常,也要处理极端场景(如从其他入口进入页面),避免参数缺失导致崩溃:
// 在使用category和item的位置增加判断 {category && item?.categoryId && ( <Text style={styles.category}> {getCategoryName(item.categoryId).toUpperCase()} </Text> )}
3. 验证导航目标屏幕名称
确保Stack Navigator中注册的屏幕名称与navigation.navigate("Recipe", ...)中的名称完全一致(大小写、拼写均需匹配),名称不匹配会导致参数无法传递。
4. 确认Drawer中的参数生成逻辑
虽然你提到Drawer中日志正常,仍需再次验证getCategoryById的返回值有效性:
const handleNavigate = () => { const randomRecipe = {}; // 确保该对象包含有效的categoryID const category = getCategoryById(randomRecipe.categoryID); console.log('待传递的category:', category); // 再次确认该日志输出有效对象 const title = category ? category.name : ""; navigation.navigate("Recipe", { item: randomRecipe, category, title }); navigation.closeDrawer(); };
5. 修复useEffect中的错误
原useEffect中使用未定义的item.recipeId,需添加判断并修正依赖项:
useEffect(() => { if (!item?.recipeId) return; // 无有效参数时终止请求 fetch('http://10.11.55.7:111/rest', { headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => { const matchedRecipe = data.find(recipe => recipe.recipeID === item.recipeId); if (matchedRecipe) { console.log(matchedRecipe.recipeID); setRecipeData(matchedRecipe); } else { console.log('No matching recipe found'); } }) .catch(error => { console.log('Fetch error:', error); }); }, [item?.recipeId]); // 添加依赖项,确保参数变化时重新请求
6. 修正组件命名一致性
Drawer组件定义为const Drawer = () => {...},但导出的是DrawerContainer,存在命名不一致问题,需统一:
const DrawerContainer = () => { // 原Drawer组件逻辑 }; DrawerContainer.propTypes = { navigation: PropTypes.shape({ navigate: PropTypes.func.isRequired, closeDrawer: PropTypes.func.isRequired, }), }; export default DrawerContainer;
内容的提问来源于stack exchange,提问作者konoha
相关产品推荐
相关产品推荐

