繁体   English   中英

未定义不是一个对象(评估'route.params.title')

[英]Undefined is not an object (evaluating 'route.params.title')

我按照 React Navigation Doc 来实现动态标题标题更改,但它显示错误 Undefined is not an object (evaluating 'route.params.title')。

我的 tabs.js:

function HomeStackScreen() {
  return (
    <HomeStack.Navigator>
      <HomeStack.Screen
        name="Home"
        component={Home}
        options={{ headerShown: false }}
      />
      <HomeStack.Screen
        name="Profile"
        component={Profile}
        options={({ route }) => ({ title: route.params.title })}
      />
    </HomeStack.Navigator>
  );
}

Home.js 有这样的 onpress:

<TouchableOpacity
  onPress={() => {
    navigation.navigate('Profile', {
      title: 'Custom title',
    });
  }}
>

和 Profile.js:

function Profile({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Hello</Text>
      <Button title="Go back" onPress={() => navigation.goBack()} />
    </View>
  );
}

在您的 params 上添加一个检查/默认值,因为 route.params 并不总是有价值的,但只有当您在该页面上导航时。

function HomeStackScreen() {
  return (
    <HomeStack.Navigator>
      <HomeStack.Screen
        name="Home"
        component={Home}
        options={{ headerShown: false }}
      />
      <HomeStack.Screen
        name="Profile"
        component={Profile}
        options={({ route }) => ({ title: route.params?.title || "DEFAULT TITLE" })}
      />
    </HomeStack.Navigator>
  );
}

暂无
暂无

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

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