React Navigation v6嵌套导航中navigation.navigate()无法调用的问题求助
嘿,我一眼就发现问题所在啦!你遇到的这个错误,根源在于Items组件接收参数的方式不正确。
问题原因
React Navigation会给每个屏幕组件传递一个包含navigation、route等属性的props对象,而你现在直接把组件的参数命名为navigation,相当于把整个props对象赋值给了这个变量——也就是说,你调用的是props.navigate,但navigate方法其实在props.navigation里面,自然就会报错啦。
你可以看看之前useEffect里的打印结果,应该会输出一个包含navigation属性的对象,而不是直接的navigation实例,这也能验证这个问题。
两种修复方案
方案1:解构props直接获取navigation
这是React开发中最常用的方式,直接从props里解构出navigation:
export default function Items({ navigation }) { useEffect(() => { console.log("ITem navi: ", navigation); }, []) return ( <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <Text>Items !</Text> <Button title="Go to Log-In" onPress={() => navigation.navigate('LogIn')} /> <AccountList /> </View> ); }
方案2:手动从props中提取navigation
如果你不习惯解构,也可以先接收完整的props,再从中取出navigation:
export default function Items(props) { const navigation = props.navigation; useEffect(() => { console.log("ITem navi: ", navigation); }, []) return ( <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <Text>Items !</Text> <Button title="Go to Log-In" onPress={() => navigation.navigate('LogIn')} /> <AccountList /> </View> ); }
选其中一种修改后,点击按钮应该就能正常跳转到LogIn页面啦!
内容的提问来源于stack exchange,提问作者Jin Park
相关产品推荐
相关产品推荐

