繁体   English   中英

TypeError: undefined is not an object(评估'route.params.myText')

[英]TypeError: undefined is not an object (evaluating 'route.params.myText')

function Screen2({route, navigation}) {
  
    
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>{route.params.myText}</Text>
      </View>
    );
  }

export default Screen2;

这里 myText 是从其他屏幕(登录屏幕)传递的字符串。

登录界面----------------------------------------

<View>
                <Button style={styles.loginBTN} title="Login"
                onPress={() => {navigation.navigate('Screen2'), {myText: "hello react-native"}}} />
            </View>

我猜有一种情况(可能在卸载之前) routeroute.params未定义,

你可以这样解决

function Screen2({route, navigation}) {  
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>

        //I added question mark before the dots (optional chaining)
        <Text>{route?.params?.myText}</Text>
      </View>
    );
  }
export default Screen2;

根据 Mozilla 的说法,它被称为可选链接

它使您能够读取位于连接对象链深处的属性的值,而无需检查链中的每个引用是否有效。

您的登录按钮按下应该传递如下参数

onPress={() = navigation.navigate("Screen2", {
          myText: "hello react-native",
        })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM