Javascript 使用电子邮件登录后无法使用firebase获取更新的配置文件信息

Javascript 使用电子邮件登录后无法使用firebase获取更新的配置文件信息,javascript,firebase,react-native,firebase-authentication,Javascript,Firebase,React Native,Firebase Authentication,我目前正在开发一个应用程序使用反应本机,我可以管理有一个登录和注册页面,但我的问题是以下。 使用firebase方法创建带有电子邮件和密码的用户后,我想更新配置文件信息(displayName),以便在主页中显示它。 但似乎在注册后页面会重定向到主页,而没有完成更新 我在导航器堆栈上设置了一个监听器,以显示登录/注册页面或主页上有关用户值的信息 如果在第一次注册成功后关闭应用并重新加载,则更新设置正确 我的代码如下 主堆栈代码 function onAuthStateChange(user) {

我目前正在开发一个应用程序使用反应本机,我可以管理有一个登录和注册页面,但我的问题是以下。 使用firebase方法创建带有电子邮件和密码的用户后,我想更新配置文件信息(displayName),以便在主页中显示它。 但似乎在注册后页面会重定向到主页,而没有完成更新

我在导航器堆栈上设置了一个监听器,以显示登录/注册页面或主页上有关用户值的信息

如果在第一次注册成功后关闭应用并重新加载,则更新设置正确

我的代码如下 主堆栈代码

function onAuthStateChange(user) {
  setUser(user);
  if (initializing) setInitializing(false);
}
useEffect(() => {
  const subscriber = auth().onAuthStateChanged(onAuthStateChange);
  return subscriber;
}, [];

if (initializing) {
return <LoadingScreen />

if (!user) {
return (
  <NavigationCOntainer>
     <AuthStackScreen />
  </NavigationCOntainer>
 );
}

return (
 <NavigationCOntainer>
    <DrawerStackScreen />
 </NavigationCOntainer>
  
在主页的代码中,我还设置了一个用户的侦听器。 我还尝试调用方法:auth().currentUser; 但我遇到了同样的问题,第一次显示时的displayName被设置为null,我必须关闭并重新加载应用程序才能显示它

function onAuthStateChange(user) {
  console.log(user);
}
useEffect(() => {
  const subscriber = auth().onAuthStateChanged(onAuthStateChange);
  return subscriber;
}, [];

日志的结果显示displayName为null,因此我假设注册过程在更新值之前重定向到home

有人知道我如何在主页屏幕上获取更新值吗

提前感谢

试试这个

function handgleRegister() {
  auth()
    .createUserWithEmailAndPassword(email, password)
    .then(userCred => {
       userCred.user.updateProfile({
           displayName: name,
       }).then(()=>{
       setUser(auth().currentUser());
    };
    })
    .catch(e => {
    ...
    ...
    });
}
这是我的注册码。我现在只是用电子邮件地址更新配置文件,因为我没有显示名称的其他输入。我也在使用redux工具包

import React, { Component, useEffect } from "react";
import { View } from "react-native";
import { Button, Input } from "react-native-elements";
import Icon from "react-native-vector-icons/FontAwesome";
import { Dimensions } from "react-native";
import auth from "@react-native-firebase/auth";
import { useDispatch, useSelector } from "react-redux";
import {
  clearLoginInfo,
  updateLoginInfo,
  signInWithEmailAndPassword,
} from "../login/LoginSlice";

export default function SignupScreen(props) {
  const { navigation } = props;
  const [username, setUsername] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [passwordErrorMsg, setPasswordErrorMsg] = React.useState("");
  const [usernameErrorMsg, setUsernameErrorMsg] = React.useState("");
  const [securedText, setSecuredTtext] = React.useState(true);
  const dispatch = useDispatch();

  function onAuthStateChanged(user) {
    console.log("on user change", user);
  }

  useEffect(() => {
    const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
    return subscriber; // unsubscribe on unmount
  }, []);

  const signIn = (e) => {
    auth()
      .createUserWithEmailAndPassword(e.username, e.password)
      .then((user) => {
        console.log("user = ", user);
        user.user
          .updateProfile({
            displayName: e.username,
            photoURL: "abc.com",
          })
          .then(() => {
            const currentUser = auth().currentUser;
            console.log("current user ", auth().currentUser);
            dispatch(
              updateLoginInfo({
                displayName: currentUser.displayName,
                photoURL: currentUser.photoURL,
              })
            );
          });
      })
      .catch((error) => {
        if (error.code === "auth/email-already-in-use") {
          setUsernameErrorMsg("That email address is already in use!");
        }
        if (error.code === "auth/invalid-email") {
          setUsernameErrorMsg("That email address is invalid!");
        }
        if (error.code === "auth/weak-password") {
          setPasswordErrorMsg("please choose a stronger password");
        }

        console.error(error);
      });
  };

  const handlePasswordChange = (val) => {
    setPassword(val);
  };

  const handleUserNameChange = (val) => {
    setUsername(val);
  };

  const doSignin = () => {
    signIn({ username, password });
  };
  return (
    <View
      style={{
        flex: 1,
        justifyContent: "center",
        alignContent: "center",
        alignItems: "center",
      }}
    >
      <Input
        placeholder="Email"
        errorMessage={usernameErrorMsg}
        value={username}
        leftIcon={{ type: "font-awesome", name: "envelope" }}
        onChangeText={handleUserNameChange}
      />
      <Input
        placeholder="Password"
        errorMessage={passwordErrorMsg}
        errorStyle={{ color: "red" }}
        value={password}
        leftIcon={<Icon name="lock" size={40} color="black" />}
        rightIcon={
          securedText ? (
            <Icon
              name="eye"
              size={32}
              onPress={() => setSecuredTtext(!securedText)}
              color="black"
            />
          ) : (
            <Icon
              name="eye-slash"
              size={32}
              onPress={() => setSecuredTtext(!securedText)}
              color="black"
            />
          )
        }
        onChangeText={handlePasswordChange}
        secureTextEntry={securedText}
      />
      <Button
        title="Sign up"
        onPress={() => doSignin()}
        buttonStyle={{ backgroundColor: "#eda621" }}
        style={{ width: Dimensions.get("window").width * 0.5 }}
      />
      <Button
        title="Back to Sign in"
        style={{ width: Dimensions.get("window").width * 0.5, marginTop: 10 }}
        onPress={() => navigation.navigate("Signin")}
      />
    </View>
  );
}

用户的配置文件信息是从其ID令牌中获取的,Firebase会获取该令牌,然后用户登录(或创建),然后每小时自动刷新一次。如果用户的配置文件在该小时内更新,则客户端可能会显示过期的配置文件信息,直到刷新令牌为止

您可以通过以下方式强制刷新令牌:

  • 再次注销和登录用户
  • 呼叫或

  • 这两种情况都会迫使客户端刷新ID令牌,从而从服务器获取最新的配置文件。

    我想注册,以便创建新用户。创建是正确的,我可以在firebase控制台中看到新用户。我的问题是更新,我无法在注册后第一次加载主页时获得更新的值。我需要关闭应用程序并重新加载它。看起来更新是异步的,所以我在完成之前重定向。但是我不能让它很好地工作。所以如果你在onAuthChange中安装一个控制台,并使用新的电子邮件注册。你得到什么了吗?新用户的创建或登录工作得很好。如果电子邮件已被使用或其他错误正常,也会显示错误。问题不在于用户的创建或登录。只有在第一次加载时才显示他们的信息更新!很抱歉。我刚刚更新了我的答案。你修改的代码,我不能使用,因为HandlerRegister函数没有setUser钩子。此寄存器函数不需要用户值。它只处理注册过程。用户的侦听器位于App.js中,这里的setUser钩子用于检查用户是否已登录或未显示正确的路由。谢谢您的回答。如果我想使用user.reload方法,如何在主页中实现它。我是否应该在onAuthStateChanged上设置一个钩子侦听器,如果用户存在,重新加载它?使用DB保存显示名称,是否最好实时更新此信息?
    import React, { Component, useEffect } from "react";
    import { View } from "react-native";
    import { Button, Input } from "react-native-elements";
    import Icon from "react-native-vector-icons/FontAwesome";
    import { Dimensions } from "react-native";
    import auth from "@react-native-firebase/auth";
    import { useDispatch, useSelector } from "react-redux";
    import {
      clearLoginInfo,
      updateLoginInfo,
      signInWithEmailAndPassword,
    } from "../login/LoginSlice";
    
    export default function SignupScreen(props) {
      const { navigation } = props;
      const [username, setUsername] = React.useState("");
      const [password, setPassword] = React.useState("");
      const [passwordErrorMsg, setPasswordErrorMsg] = React.useState("");
      const [usernameErrorMsg, setUsernameErrorMsg] = React.useState("");
      const [securedText, setSecuredTtext] = React.useState(true);
      const dispatch = useDispatch();
    
      function onAuthStateChanged(user) {
        console.log("on user change", user);
      }
    
      useEffect(() => {
        const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
        return subscriber; // unsubscribe on unmount
      }, []);
    
      const signIn = (e) => {
        auth()
          .createUserWithEmailAndPassword(e.username, e.password)
          .then((user) => {
            console.log("user = ", user);
            user.user
              .updateProfile({
                displayName: e.username,
                photoURL: "abc.com",
              })
              .then(() => {
                const currentUser = auth().currentUser;
                console.log("current user ", auth().currentUser);
                dispatch(
                  updateLoginInfo({
                    displayName: currentUser.displayName,
                    photoURL: currentUser.photoURL,
                  })
                );
              });
          })
          .catch((error) => {
            if (error.code === "auth/email-already-in-use") {
              setUsernameErrorMsg("That email address is already in use!");
            }
            if (error.code === "auth/invalid-email") {
              setUsernameErrorMsg("That email address is invalid!");
            }
            if (error.code === "auth/weak-password") {
              setPasswordErrorMsg("please choose a stronger password");
            }
    
            console.error(error);
          });
      };
    
      const handlePasswordChange = (val) => {
        setPassword(val);
      };
    
      const handleUserNameChange = (val) => {
        setUsername(val);
      };
    
      const doSignin = () => {
        signIn({ username, password });
      };
      return (
        <View
          style={{
            flex: 1,
            justifyContent: "center",
            alignContent: "center",
            alignItems: "center",
          }}
        >
          <Input
            placeholder="Email"
            errorMessage={usernameErrorMsg}
            value={username}
            leftIcon={{ type: "font-awesome", name: "envelope" }}
            onChangeText={handleUserNameChange}
          />
          <Input
            placeholder="Password"
            errorMessage={passwordErrorMsg}
            errorStyle={{ color: "red" }}
            value={password}
            leftIcon={<Icon name="lock" size={40} color="black" />}
            rightIcon={
              securedText ? (
                <Icon
                  name="eye"
                  size={32}
                  onPress={() => setSecuredTtext(!securedText)}
                  color="black"
                />
              ) : (
                <Icon
                  name="eye-slash"
                  size={32}
                  onPress={() => setSecuredTtext(!securedText)}
                  color="black"
                />
              )
            }
            onChangeText={handlePasswordChange}
            secureTextEntry={securedText}
          />
          <Button
            title="Sign up"
            onPress={() => doSignin()}
            buttonStyle={{ backgroundColor: "#eda621" }}
            style={{ width: Dimensions.get("window").width * 0.5 }}
          />
          <Button
            title="Back to Sign in"
            style={{ width: Dimensions.get("window").width * 0.5, marginTop: 10 }}
            onPress={() => navigation.navigate("Signin")}
          />
        </View>
      );
    }
    
    useEffect(()=>{
       if (user != null && user.displayName != '') {
         navigation.navigate("Home");
       },
       [user]});