【问题标题】:Cannot read property of undefined in react navigation native with typescript无法使用打字稿读取本机反应导航中未定义的属性
【发布时间】:2020-10-12 16:15:14
【问题描述】:

我正在构建一个 react native 应用程序,但在使用 react-navigation/native 将道具传递到另一个屏幕时遇到问题。

导航设置

export type RootStackParamList = {
  Home: HomeProps,
  LoginDemo: undefined,
  Login: undefined
};

const Stack = createStackNavigator<RootStackParamList>();
const store = configureStore();

export const Navigation: React.FC = () => {

  return (
    <Provider store={store}>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="LoginDemo" component={LoginDemo} />
          <Stack.Screen name="Home" component={Home}/>
          <Stack.Screen name="Login" component={LoginScreen} />
        </Stack.Navigator>
      </NavigationContainer>
    </Provider>
  );
};

进行屏幕切换的代码

React.useEffect(() => {
    if (patrolUnits.completed) {
      if (patrolUnits.error !== null)
        showAlert("error", patrolUnits.error.toString());
      else
        navigation.replace('Home', {patrolUnitId: patrolUnits.data[0].id});
    }

  }, [patrolUnits.completed]);

我要切换到的屏幕

export const Home: React.FC<RouteProp<RootStackParamList, "Home">> = routeProps => {

    const props = routeProps.params;

    const { patrolUnitId } = props;

    return (<View>
        <Text>{patrolUnitId.toString()}</Text>
    </View>)
};

以及应该通过的道具

export type HomeProps = {

    patrolUnitId: number;

}

谁能告诉我我做错了什么。几个小时以来,我一直试图弄清楚这一点。我试过谷歌搜索,但几乎所有推荐给我的都是常规反应,而不是原生反应。

【问题讨论】:

    标签: typescript react-native react-navigation


    【解决方案1】:

    你快到了。问题在于这个声明:

    React.FC<RouteProp<RootStackParamList, "Home">>
    

    RouteProp 类型定义了作为 route 传递的道具的类型。在这里,您声明 RouteProp 是组件的整个道具,而不是称为 route 的单个道具。

    你想要:

    const Home: React.FC<{route: RouteProp<RootStackParamList, "Home">}> = ({route}) => {
    

    每个Stack.Screen 的渲染组件将使用属性navigation(类型StackNavigationProp)和route(类型RouteProp)调用。还有一个类型StackScreenProps,它定义了一个具有两个道具的对象。所以你也可以这样做:

    const Home: React.FC<StackScreenProps<RootStackParamList, "Home">> = ({route}) => {
    

    在带有useEffect 钩子的组件上,您需要确保navigation 包含在props 中并且输入正确。

    你可以使用:

    type MyComponentProps = {
        navigation: StackNavigationProp<RootStackParamList, "Name">
    }
    

    type MyComponentProps = StackScreenProps<RootStackParamList, "Name">
    

    Expo Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      相关资源
      最近更新 更多