【问题标题】:Getting "undefined" when passing params using react-navigation version 5?使用 react-navigation 版本 5 传递参数时得到“未定义”?
【发布时间】:2020-09-07 01:26:20
【问题描述】:

TLDR:我没有在 react-navigation 5 中使用 route.params 将参数从一个屏幕传递到下一个屏幕。

我刚刚从 react-navigation 版本 4 更新到版本 5。我现在在屏幕之间传递参数时遇到问题。在我正在导航的屏幕中,我使用 onPress() 导航到下一个屏幕并在参数“loveOne”中传递一个字符串“son”。

从第一个屏幕开始,这里是重要的代码:

import { useNavigation } from '@react-navigation/native';
.
.
.
class RegistrationPageTwo extends React.Component {
.
.
.
    render(){
        const { radiochecked } = this.state;
        const { navigation } = this.props;
.
.
.
        onPress={() => {navigation.navigate('RegistrationThree', { params: { loveOne: "son" },})}}
.
.
.
// Wrap and export
export default function(props) {
    const navigation = useNavigation();

    return <RegistrationPageTwo {...props} navigation={navigation} />;
}

在被调用的屏幕“RegistrationPageThree”中,我执行以下操作:

import { useNavigation, useRoute } from '@react-navigation/native';
.
.
.
    render(){
        const { route } = this.props
        const { loveOne } = route.params;
        console.log("entering render section: " + loveOne );
.
.
.
// Wrap and export
export default function(props) {
    const route = useRoute();

    return <RegistrationPageThree {...props} route={ route } />;
  } 

I am getting "undefined" for loveOne in the consolelog statement.

I have been over the react-navigation 5 documentation and can't seem to pull out what I am doing wrong.
Thanks for the help!

Garry O.

【问题讨论】:

    标签: react-native react-navigation react-navigation-v5


    【解决方案1】:

    您传递参数的方式用于嵌套导航器,在您使用直接导航的情况下,您只需更改此行

    onPress={() => {navigation.navigate('RegistrationThree', {  loveOne: "son" })}}
    

    您未定义的原因是您的变量包含在参数中

    【讨论】:

    • 谢谢古鲁帕兰!它修复了它。我在屏幕堆栈下方有一个嵌套导航(堆栈+抽屉),并假设这是调用无论您在哪个导航堆栈中的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 2018-11-14
    • 2020-12-22
    • 2020-05-23
    相关资源
    最近更新 更多