【问题标题】:can't find variable: user.I am using firebase auth and the latest SDK, expo SDK 42, react navigation 6.x.x找不到变量:用户。我正在使用 firebase auth 和最新的 SDK、expo SDK 42、react navigation 6.x.x
【发布时间】:2021-12-04 10:55:30
【问题描述】:
import React, { useEffect } from "react";
import { StyleSheet, Text, 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() {
  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      console.log(user);
      return user;
    });
    return unsubscribe;
  }, []);

  return (
    <NavigationContainer>
      <Stack.Navigator>
        {user ? (
          <>
            <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.Screen
            options={{ headerShown: false }}
            name="Welcome"
            component={WelcomeScreen}
          />
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
}

找不到变量:用户, 我也无法理解我是 react-native 和 react-navigation 的新手。我尝试了返回用户但没有划线或其他东西。

试过

const isLoggedIn = user;
console.log(isLoggedIn)

它只是记录未定义。 有人可以帮我吗?

我正在使用 firebase auth 和最新的 SDK、expo SDK 42、react navigation 6.x.x 当应用程序加载并且用户通过身份验证时,使用条件渲染隐藏 onBoarding、logIn 和 signUp 屏幕,因此他直接对welcomeScreen 进行操作

链接到世博小吃。在您的设备上运行它而不是在网络上。 https://snack.expo.dev/@bishalsaha/a638cf

【问题讨论】:

  • 您正在从您自己的文件权限“./firebase”中导入身份验证,请分享该代码以便于识别问题
  • import * as firebase from "firebase"; const firebaseConfig = { apiKey: "AIzaSyA5nLMFvIitIBjwSJbAV0bNVYwPS_FwoyA", authDomain: "app-rupee.firebaseapp.com", projectId: "app-rupee", storageBucket: "app-rupee.appspot.com", messagingSenderId: "562775444152", appId: "1:562775444152:web:4c68256cf269be43d3c24d", measurementId: "G-E2M06JHH8M", }; let app; if (firebase.apps.length === 0) { app = firebase.initializeApp(firebaseConfig); } else { app = firebase.app(); } const auth = firebase.auth(); export { auth };

标签: firebase react-native firebase-authentication expo react-navigation


【解决方案1】:

提示:您可能需要重新生成您在评论中公开的 api 密钥!

假设您的身份验证工作正常并且您的登录 useEffect 没有未定义,您的应用可能会修复您处理用户变量的方式:

export default function App() {
  const [isLoggedIn, setIsLoggedIn] = React.useState(false);
  const [user, setUser] = React.useState();
  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((receivedUser) => {
      console.log(receivedUser);
      setUser(receivedUser);
      setIsLoggedIn(true);
    });
    unsubscribe();
  }, []);

  // Check your logs
  console.log(user);
  console.log(isLoggedIn);

  return (
    <NavigationContainer>
      <Stack.Navigator>
        {user ? (
          <>
            <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.Screen
            options={{ headerShown: false }}
            name="Welcome"
            component={WelcomeScreen}
          />
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
}

编辑: 根据您关于重新加载后保持状态的问题:

正如React Native Docs 中提到的,存储状态是由称为 AsyncStorage 和 Secure Storage 的东西提供的。 异步存储适用于所有适用于 graphql 或持久状态管理的东西。

由于您的用户电子邮件和密码属于敏感数据类别,我强烈建议您使用expo-secure-storage。 如果您不想进行重构,我会在您提供的示例中更改 handleLogin 函数:

import * as SecureStore from 'expo-secure-store';

// [your components code]

 const handleLogin = () => {
    let data = await SecureStore.getItemAsync(userCredsKey);
    userCreds = userCreds ? JSON.parse(data)
    if (!userCreds) {
      userCreds = { email: email, password: password };
    }
    auth
      .signInWithEmailAndPassword(userCreds.email, userCreds.password)
      .then((userCredentials) => {
        const user = userCredentials.user;
        console.log("Logged in with:", user.email);
        //login successfull
        await SecureStorage.setItemAsync(userCredsKey, JSON.stringify(userCreds));
      })
      .catch((error) => alert(error.message));
  };

注意:以上代码仅展示了如何在重新加载应用程序后使用安全存储和登录用户的想法。 您可能想在这里走另一条路,或者甚至更好地将逻辑与专用服务文件中的组件解耦:-)

【讨论】:

  • 嘿伙计,我还有问题。当我重新加载应用程序时,用户未定义。可能是因为它没有等待从 firebase 检查身份验证状态。你能帮我解决这个问题吗?
  • 您可以使用异步存储或更好的钥匙串存储在重新加载后保存您的用户数据。我将在当天晚些时候更新我的答案:-)
【解决方案2】:

使用本地存储

我遇到了同样的问题,我使用本地存储来保存用户数据,在刷新或重新加载应用程序时,将从本地存储中获取数据。这就是我在网络上处理问题的方式。

// useState
    const [currentUser, setCurrentUser] = useState(() => {
      const data = localStorage.getItem("currentUser"); // Get data from local storage when the app is reloaded or refreshed. If there is some data in local storage the app will use that.
      return data ? JSON.parse(data) : {};
    });



// useEffect
seEffect(() => {
  const unsubscribe = auth.onAuthStateChanged(user => {
    localStorage.setItem("currentUser", JSON.stringify(user)); // Saving user to your app local storage
    setCurrentUser(user);
  })
  return unsubscribe
}, [])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 2019-06-25
    相关资源
    最近更新 更多