如何解决 route.params undefined in react native screens typescript

How to solve route.params undefined in react native screens typescript

我在下面有这个,我从 API 中获取国家名称,并使用 routes 在屏幕上显示它们。现在,我想将 item.country 显示为 headerTitle。但是,我收到 route.params.undefined 错误,我该如何解决这个问题?

LocationDataScreen.tsx

function LocationDataScreen({ route, navigation }) {
  const { item } = navigation.state.params || {};  
  const countryName = item.country;
  return (
    <View style={styles.container}>
      <Text>{countryName}</Text>
      <Text>{item.cases}</Text>
    </View>
  );
}

ItemView.tsx

const ItemView = ({ item }) => {
    return (
      <RectButton
        onPress={() =>
          navigate("LocationDataScreen", { item: item, name: item.country })
        }
      >
        <Text style={[styles.itemStyle, { textTransform: "capitalize" }]}>
          {item.id}
          {item.country.toUpperCase()}
        </Text>
      </RectButton>
    );
  };

App.tsx

<AppStack.Navigator initialRouteName="SearchScreen">
  <AppStack.Screen name="SearchScreen" component={SearchScreen} />
  <AppStack.Screen
          name="LocationDataScreen"
          component={LocationDataScreen}
          options={({ route }) => ({
            headerLargeTitle: true,
            title: route.params.item,
          })}
        /> 

你应该像下面那样做

options={({route}) => ({
            headerLargeTitle: true,
            title: route.params.name,
          })}

您必须像下面那样传递名称

navigation.navigate("LocationDataScreen",{name:item.name});

确保您具有如下设置以访问参数

import { createStackNavigator } from '@react-navigation/stack';

type RootStackParamList = {
  SearchScreen: undefined;
  LocationDataScreen: { name: string };
};

const AppStack = createStackNavigator<RootStackParamList>();

问题只是您以错误的方式将参数传递给 LocationDataScreen.tsx

改用这个:

ItemView

const ItemView = ({ item }) => {
    return (
      <RectButton
        onPress={() =>
          navigate("LocationDataScreen", { ...item })
        }
      >
        <Text style={[styles.itemStyle, { textTransform: "capitalize" }]}>
          {item.id}
          {item.country.toUpperCase()}
        </Text>
      </RectButton>
    );
  };

LocationDataScreen.tsx

function LocationDataScreen({ route, navigation }) {
  const { country, cases } = route.params

  return (
    <View style={styles.container}>
      <Text>{country}</Text>
      <Text>{cases}</Text>
    </View>
  );
}

我假设您在这一行 const ItemView = ({ item }) => { 中的 item 看起来像这样。

item: {
   country: 'Italy',
   cases: 10
}

如果您可以添加 api 回复 here。 添加后请在评论中告诉我。同时在评论中分享link。