"Undefined" 在 React Navigation 中将参数传递到另一个屏幕时出错
"Undefined" error when passing params to another screen in React Navigation
我有 2 个屏幕,EditProfile 和 Profile。我正在尝试将编辑后的名称和日期从 EditProfile 传递到 Profile。它们都堆叠在 ProfileNavigator 中,Profile 是出现的第一个屏幕,用户可以从那里点击编辑配置文件按钮并导航到编辑配置文件屏幕。我如何将更新的编辑屏幕名称和日期参数传递给主配置文件?以下代码不起作用并且 return 无法读取 属性 未定义的“日期”:
const EditProfileScreen = () => {
const navigation = useNavigation();
}
return (
..
<TouchableOpacity style={styles.commandButton} onPress= {() => {navigation.navigate("Profile", {params: {date: date, name: name }})} }
activeOpacity={0.5}>
<Text style={styles.panelButtonTitle}>Submit</Text>
</TouchableOpacity>
);
虽然这是配置文件屏幕的代码:
const ProfileScreen = ({route, navigation}) => {
const { date } = route.params;
const { name } = route.params;
return (
..
<Text>{JSON.stringify(date)}</Text>
<Text>{JSON.stringify(name)}</Text>
)
您的方法没有任何问题,但您缺少对个人资料屏幕初始呈现的空处理。
这样想,您第一次导航到配置文件屏幕时不会出现 route.params,因为您没有传递任何最终会出错的参数。
但是当您转到编辑屏幕并返回参数时,您将拥有 route.params,您可以毫无问题地访问它。
所以像这样更改您的代码
<Text>{JSON.stringify(route.params?.date)}</Text>
<Text>{JSON.stringify(route.params?.name)}</Text>
或者,如果您的个人资料对象处于个人资料屏幕的状态,请根据 route.params 的变化使用 useEffect 挂钩对其进行更新。
我有 2 个屏幕,EditProfile 和 Profile。我正在尝试将编辑后的名称和日期从 EditProfile 传递到 Profile。它们都堆叠在 ProfileNavigator 中,Profile 是出现的第一个屏幕,用户可以从那里点击编辑配置文件按钮并导航到编辑配置文件屏幕。我如何将更新的编辑屏幕名称和日期参数传递给主配置文件?以下代码不起作用并且 return 无法读取 属性 未定义的“日期”:
const EditProfileScreen = () => {
const navigation = useNavigation();
}
return (
..
<TouchableOpacity style={styles.commandButton} onPress= {() => {navigation.navigate("Profile", {params: {date: date, name: name }})} }
activeOpacity={0.5}>
<Text style={styles.panelButtonTitle}>Submit</Text>
</TouchableOpacity>
);
虽然这是配置文件屏幕的代码:
const ProfileScreen = ({route, navigation}) => {
const { date } = route.params;
const { name } = route.params;
return (
..
<Text>{JSON.stringify(date)}</Text>
<Text>{JSON.stringify(name)}</Text>
)
您的方法没有任何问题,但您缺少对个人资料屏幕初始呈现的空处理。
这样想,您第一次导航到配置文件屏幕时不会出现 route.params,因为您没有传递任何最终会出错的参数。
但是当您转到编辑屏幕并返回参数时,您将拥有 route.params,您可以毫无问题地访问它。
所以像这样更改您的代码
<Text>{JSON.stringify(route.params?.date)}</Text>
<Text>{JSON.stringify(route.params?.name)}</Text>
或者,如果您的个人资料对象处于个人资料屏幕的状态,请根据 route.params 的变化使用 useEffect 挂钩对其进行更新。