开发者问题收集

TypeError:未定义不是一个对象(评估“route.params”)

2020-06-05
7195

我设置了一个带有各种屏幕的 Drawer Navigator。

在一个屏幕上,我有一个带有简单 TouchableOpacity 的 FlatList,如下所示:

 <TouchableOpacity
              onPress={() =>
                navigation.navigate("ViewProject", {
                  screen: "viewProject",
                  params: { projectID: item.projectID },
                })
              }
            >
 </TouchableOpacity>

导航有效,转到 viewProject 屏幕,但无论我如何尝试,route.params 似乎都不存在。

  export default function viewProject({ route }) {
  const projID = route.params?.projectID ?? 0; // ERRORS with TypeError: undefined is not an object (evaluating 'route.params')
  console.log(projID); 

我正在使用最新的 React Native、Navigation 等和 TypeScript。

我唯一的成功是在 createStackNavigator 上设置了 initialRouteParams,该 createStackNavigator 会输入到抽屉中,但这只能通过 navigation.state.params 访问:

const screens = {
  viewProject: {
    screen: viewProject,   
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: () => (
          <Header navigation={navigation} title={"View Project"} />
        ),
      };
    },
  },
};

const viewProjectStack = createStackNavigator(screens, {
  initialRouteParams: { projectID: 23 }, // This works, but it's static and I can't change it  
});

提前致谢。 Stewart

1个回答

您可以像这样传递:-

<Button
title="Go to Details"
onPress={() => {
  /* 1. Navigate to the Details route with params */
  navigation.navigate('Details', {
    itemId: 86,
    otherParam: 'anything you want here',
  });
}}

/>

并像这样接收:-

function DetailsScreen({ route, navigation }) {
 /* 2. Get the param */
 const { itemId } = route.params;
const { otherParam } = route.params;
 return (
 <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
 <Text>itemId: {JSON.stringify(itemId)}</Text>
 <Text>otherParam: {JSON.stringify(otherParam)}</Text>
  );
  }

source

希望有帮助!!!

Shahanshah Alam
2020-06-05