react-navigation v5升级后如何获取路由传递的博客文章id参数
修正方案
核心变更说明
react-navigation v5 废弃了原来的 navigation.getParam() 方法,路由参数统一从 route 对象的 params 属性中获取。
第一步:修改 ShowScreen 页面代码
修正后的完整代码如下:
import React, { useContext } from 'react'; import { View, Text, StyleSheet } from 'react-native'; import { Context } from '../../context/BlogContext'; // 组件props新增route参数,所有跳转传递的参数都存在route.params里 const ShowScreen = ({ route }) => { const { state } = useContext(Context); // 直接从route.params取id,不需要再用navigation.getParam const id = route.params.id; const blogPost = state.find(blogPost => blogPost.id === id); return ( <View> {/* 不能直接渲染整个对象,按需取对应字段即可,比如标题、内容 */} <Text>标题:{blogPost?.title}</Text> <Text>内容:{blogPost?.content}</Text> </View> ); }; const styles = StyleSheet.create({}); export default ShowScreen;
ShowScreen 调整点说明
- 移除了重复引入的
useNavigation和重复声明的navigation变量,避免命名冲突 - 从组件 props 中解构出
route对象,所有跳转携带的参数都存储在route.params下 - 渲染时避免直接输出整个
blogPost对象,按需读取对象内的字段,添加可选链?.避免查询不到内容时报错
如果你的组件不方便拿props的route,也可以用useRoute钩子获取参数:
import { useRoute } from '@react-navigation/native'; // 组件内部调用 const route = useRoute(); const id = route.params.id;
第二步:修复 IndexScreen 页面的已知问题
你当前的IndexScreen存在两处隐性错误,同步修正即可:
// 省略其他未改动代码 // 1. 修正拼写错误:navigationOpitions → navigationOptions IndexScreen.navigationOptions = ({ navigation }) => { return { headerRight: () => ( // 2. 从navigationOptions的参数中拿到navigation,再调用navigate方法 <TouchableOpacity onPress={() => navigation.navigate('Create')}> <Feather name="plus" size={30} /> </TouchableOpacity> ), }; } // 省略其他未改动代码
IndexScreen 调整点说明
- 修复了
navigationOptions的拼写错误,原来少写了一个t,会导致头部配置不生效 - 给
navigationOptions传入navigation参数,避免调用navigation.navigate时报未定义的错误
内容的提问来源于stack exchange,提问作者user11240162
相关产品推荐
相关产品推荐

