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

React Navigation中route.params为undefined及uid读取报错问题

问题修复方案

1. 修正uid的错误解构

你当前代码里的const {uid} = route.params.uid;写法有误——route.params.uid是字符串类型的用户ID,不能对字符串做对象解构。改成以下两种正确写法之一:

// 写法1:直接从route.params对象中解构uid
const { uid } = route.params;

// 写法2:直接读取params里的uid属性
const uid = route.params.uid;

同时为了避免route.params为undefined导致报错,可以加兜底处理:

const { uid } = route.params || {};
// 或者
const uid = (route.params || {}).uid;

2. 修复Search页面的跳转逻辑

Tab.Screen本身没有onPress属性,你写的跳转逻辑不会生效。可以通过两种方式修复:

方式1:在SearchUsers组件内部处理跳转

在搜索页面的交互元素上绑定跳转事件:

// SearchUsers组件示例
const SearchUsers = ({ navigation }) => {
  return (
    {/* 示例:点击搜索页面容器跳转 */}
    <TouchableOpacity 
      onPress={() => navigation.push('Profile', {
        uid: firebase.auth().currentUser?.uid
      })}
    >
      {/* 搜索页面内容 */}
    </TouchableOpacity>
  );
};

方式2:自定义Tab的按钮组件

直接在Tab.Screen的options里自定义tab按钮:

<Tab.Screen
  name="Search"
  component={SearchUsers}
  options={{
    tabBarShowLabel: false,
    headerShown: false,
    tabBarButton: (props) => (
      <TouchableOpacity
        {...props}
        onPress={() => {
          props.navigation.push('Profile', {
            uid: firebase.auth().currentUser?.uid
          });
        }}
      >
        <Icon name="search-outline" color={props.color} size={props.size} />
      </TouchableOpacity>
    )
  }}
/>

3. 确保ProfileStack传递参数

因为Profile页面嵌套在ProfileStack里,需要保证Stack的根组件把参数传递给Profile页面。如果ProfileStack是一个Stack导航器,参考以下写法:

const ProfileStack = createStackNavigator();

export default function ProfileStackScreen({ route, navigation }) {
  return (
    <ProfileStack.Navigator>
      <ProfileStack.Screen
        name="ProfileScreen"
        component={Profile}
        initialParams={route.params} // 将收到的参数传递给Profile页面
      />
    </ProfileStack.Navigator>
  );
}

4. 逻辑代码的兜底处理

在Profile组件的useEffect里先判断uid是否存在,避免后续逻辑报错:

useEffect(() => {
  if (!uid) return;
  
  if (uid === firebase.auth().currentUser?.uid) {
    setUser(currentUser);
    setUserPosts(posts);
  }
}, [uid, currentUser, posts]);

内容的提问来源于stack exchange,提问作者Moeed Sarwar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 14:02:13