React Navigation报错:无法读取undefined的navigate属性,求排查
你遇到的Uncaught TypeError: Cannot read properties of undefined (reading 'navigate')错误,核心问题出在组件接收导航属性的方式上:
错误原因
React函数组件的参数只有一个props对象,你错误地将navigation作为第二个独立参数接收,导致navigation变量为undefined,调用navigate时自然触发报错。
修正方案
方案1:解构props中的navigation
直接从props对象里解构出navigation属性:
const TripsProfileScreen: FunctionComponent<TripsSectionProfileProps> = ({ navigation }) => { return ( <Container> <IconButton onPress={() => navigation.navigate('NewTrip')} /> </Container> ) }
方案2:通过props对象访问navigation
保留完整的props参数,直接通过props.navigation调用方法:
const TripsProfileScreen: FunctionComponent<TripsSectionProfileProps> = (props) => { return ( <Container> <IconButton onPress={() => props.navigation.navigate('NewTrip')} /> </Container> ) }
额外说明
如果TripsProfileScreen不是直接作为Stack.Screen的component属性渲染的嵌套组件,需要使用useNavigation钩子获取导航对象:
import { useNavigation } from '@react-navigation/native'; const TripsProfileScreen: FunctionComponent<TripsSectionProfileProps> = () => { const navigation = useNavigation(); return ( <Container> <IconButton onPress={() => navigation.navigate('NewTrip')} /> </Container> ) }
内容的提问来源于stack exchange,提问作者Glenncito
相关产品推荐
相关产品推荐

