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

Expo SDK42+Firebase Auth+React Navigation6找不到user变量问题求助

问题原因
  • 变量作用域错误:你在onAuthStateChanged回调里拿到的user是回调函数的局部变量,仅能在回调内部访问,你在回调里return user没有任何作用,外部的渲染逻辑根本访问不到这个变量,所以才会报can't find variable: user的错误。
  • 没有使用状态管理:React 组件的渲染只会响应state或props的变化,你没有把认证状态存在组件状态中,就算拿到了用户信息,组件也不会触发重新渲染,条件判断永远无法拿到最新的认证状态。
  • 条件逻辑写反:你现有的三元表达式逻辑是「有user时显示登录注册引导页,无user时显示欢迎页」,和你需要的「已认证进欢迎页,未认证进登录注册」的需求完全相反。
  • 缺失Hook导入:你代码中使用了useEffect但没有从react包中导入相关Hook,也会触发运行时错误。
修复方案

直接替换你的App.js代码为以下版本即可:

import React, { useState, useEffect } from 'react';
import { ActivityIndicator, View } from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import LoginScreen from "./screens/LoginScreen";
import SignUpScreen from "./screens/SignUpScreen";
import WelcomeScreen from "./screens/WelcomeScreen";
import OnBoard from "./screens/Onboard";
import GetStarted from "./screens/GetStarted";
import { auth } from "./firebase";

const Stack = createNativeStackNavigator();

export default function App() {
  // 存储用户认证状态
  const [user, setUser] = useState(null);
  // 存储Firebase初始化加载状态,避免闪屏
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      setUser(user);
      setLoading(false);
    });
    return unsubscribe;
  }, []);

  // 加载中显示加载指示器
  if (loading) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <ActivityIndicator size="large" />
      </View>
    )
  }

  return (
    <NavigationContainer>
      <Stack.Navigator>
        {user ? (
          // 已认证:只显示欢迎页
          <Stack.Screen
            options={{ headerShown: false }}
            name="Welcome"
            component={WelcomeScreen}
          />
        ) : (
          // 未认证:显示引导、注册、登录页
          <>
            <Stack.Screen
              options={{ headerShown: false }}
              name="OnBoard"
              component={OnBoard}
            />
            <Stack.Screen
              options={{ headerShown: false }}
              name="SignUp"
              component={SignUpScreen}
            />
            <Stack.Screen
              options={{ headerShown: false }}
              name="Login"
              component={LoginScreen}
            />
          </>
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
}
额外说明
  • 新增的loading状态是为了避免Firebase初始化认证状态的间隙,未认证页面短暂闪现的问题,加载过程中会先显示全屏加载指示器
  • onAuthStateChanged返回的取消监听函数已经在useEffect的清理函数中返回,不会出现内存泄漏问题
  • 你后续如果需要在其他页面访问用户信息,可以直接从auth.currentUser获取,或者通过路由参数传递即可

内容的提问来源于stack exchange,提问作者BISHAL SAHA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:36:02