TypeError:未定义不是一个对象(评估“route.params.myText”)
2022-01-23
492
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>
2个回答
我猜有一种情况(可能在卸载之前)是
route
或
route.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
It enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.
Sima Ghoreyshi
2022-01-23
您按下登录按钮应传递如下参数
onPress={() = navigation.navigate("Screen2", {
myText: "hello react-native",
})
}
Sourav Dey
2022-01-31