You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native登录页向首页传参报错:Cannot read property 'tasks' of undefined

问题原因

你遇到的问题是参数传递层级不对:Login里通过navigation.navigate('Home', {tasks: res.data.tasks})把参数传给了Stack导航中的Home屏(也就是RootHome组件),但你的Home.js是Tab导航里HomeTab对应的子组件,它的route.params不会直接拿到Stack传过来的参数,所以才会出现Cannot read property 'tasks' of undefined。

解决方案

步骤1:修改RootHome组件,传递参数给Home

在App.js的RootHome组件中,接收route参数,再通过initialParams把参数传递给HomeTab对应的Home组件:

const RootHome = ({ route }) => {
  return (
    <Tab.Navigator
      initialRouteName="HomeTab"
      screenOptions={{
        tabBarActiveTintColor: '#42c983',
        headerShown: false,
        tabBarStyle: {
          backgroundColor: '#265c6f',
          height: 60,
        },
        tabBarLabelStyle: {
          fontFamily: 'UbuntuSans-Regular',
          fontSize: 14,
          marginBottom: 5,
        },
        tabBarHideOnKeyboard: true,
      }}>
      <Tab.Screen
        name="HomeTab"
        component={Home}
        // 将RootHome拿到的参数传递给Home组件
        initialParams={{ tasks: route.params?.tasks }}
        options={{
          tabBarLabel: 'Task',
          tabBarInactiveTintColor: 'white',
          tabBarIcon: ({color}) => (
            <Icon name="tasks" color={color} size={20} />
          ),
        }}></Tab.Screen>

      <Tab.Screen
        name="AccountTab"
        component={Account}
        options={{
          tabBarLabel: 'Account',
          tabBarInactiveTintColor: 'white',
          tabBarIcon: ({color}) => (
            <Icon2 name="account" color={color} size={24} />
          ),
        }}></Tab.Screen>
    </Tab.Navigator>
  );
};

步骤2:修改Home.js,增加容错处理

在Home.js中使用可选链操作符?.,避免route.params为undefined时抛出错误:

const Home = ({route}) => {
  const tasks = route.params?.tasks;
  console.log(tasks);
  // 后续业务逻辑代码
};

额外优化(可选)

如果希望参数在Tab导航切换后依然保留,也可以用React Context或Redux这类状态管理方案,但当前场景用上述方法已经足够解决问题。

内容的提问来源于stack exchange,提问作者Romeo Kurniawan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 20:35:04