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

Firebase v9 Auth在React-Native Expo中displayName提交后不即时显示求助

问题描述

在React-Native Expo项目中使用Firebase v9 Auth实现注册功能时,提交表单后displayName已被成功设置,但必须重启应用才能在首页显示,首次重定向后无法展示该字段。希望实现提交完成后重定向即可直接加载displayName的效果。

提交相关的authContext函数

const isSignUp = async (email, password, displayName) => {
    const {user} = await createUserWithEmailAndPassword(authentication,email, password)
    await updateProfile(user, {
        'displayName': displayName
    })
}

提交函数

const onSignUpPressed = async (data) =>{
    console.log(data)
   await isSignUp(email, password, displayName )
    .then((res) => {
      // console.log(res)
  
      })
    .catch((error) => {
      console.log(error);
      switch(error.code) {
        case "auth/email-already-in-use" : alert("Un compte utilise déjà cet email");
        break
      }
    })
    .finally(() => mounted.current)
  }

渲染组件

return (
    // <ScrollView showsVerticalScrollIndicator={false}>
        <ImageBackground 
          source={image} 
          resizeMode="cover" 
          imageStyle={{opacity:.05}}
          style={styles.imageBackground}
          >
          <SafeAreaView style={styles.signupContainer}>
              <View style={styles.textContainer}>
                <Text style={styles.text}>Créer un compte</Text>
              </View>
              <CustomInputText 
                  name="pseudo"
                  placeholder="Pseudo"
                  control={control}
                  rules={{
                    required: "Veuillez entrer un pseudo",
                    minLength : {value: 3, message: "3 caractères minimum"},
                    maxLength : {value: 20, message: "20 caractères maximum"},
                    }}
                  />
              <CustomInputText 
                  placeholder="Email"
                  name="email"
                  control={control}
                  rules={{
                    required: "Veuillez entrer un email",
                    pattern: {
                      value: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
                      message: "Veuillez entrer un Email valide",
                      },
                    }}
                  />
              <CustomInputPassword 
                  placeholder="Mot de passe"
                  name="password"
                  control={control}
                  secureTextEntry
                  rules={{
                    required: "Veuillez entrer un mot de passe",
                    minLength : {value: 8, message: "8 caractères minimum"},
                  }}
                  isShowIcon={true}
                  />
              <CustomInputPassword 
                  placeholder="Confirmer le mot de passe"
                  name="confirm-password"
                  control={control}
                  secureTextEntry
                  rules={{
                    required: "Veuillez entrer un mot de passe",
                    validate: value => value === password ? true : "Le mot de passe ne correspond pas"
                  }}
                  isShowIcon={true}
                  />

                <CustomButton
                  text="Créer un compte"
                  onPress={handleSubmit(onSignUpPressed)}
                  />

                <SocialSignInButton />

                <CustomButton
                  text={'Déja un compte ? Se connecter'}
                  onPress={onSigneIn}
                  type={'SECOND'}
                  />
                <Text style={styles.textConditions}>
                  En vous inscrivant, vous acceptez les <Text style={styles.textConditionsLink} onPress={onTermOfUser}>Conditions d'Utilisation</Text> et la <Text style={styles.textConditionsLink} onPress={onPrivacyPolicy}>Politique de Confidentialité</Text>, incluant l'<Text style={styles.textConditionsLink} onPress={onCookiesUtilisationst}>Utilisation de Cookies.</Text>
                </Text>
        </SafeAreaView>
      </ImageBackground>

  // </ScrollView>
    
  )
}
解决方案

问题根源是:调用updateProfile更新用户displayName后,Firebase Auth不会自动触发onAuthStateChanged监听事件,而首页依赖的用户信息可能还是之前缓存的旧数据,因此重定向后无法立即看到更新后的displayName。

修复步骤:

  1. 修改isSignUp函数,返回更新后的用户对象
const isSignUp = async (email, password, displayName) => {
    const { user } = await createUserWithEmailAndPassword(authentication, email, password);
    await updateProfile(user, {
        displayName: displayName
    });
    // 返回更新后的用户实例
    return user;
}
  1. 统一onSignUpPressed的异步处理逻辑,并手动更新Auth Context中的用户状态
    假设你的Auth Context中存在setCurrentUser用于管理当前登录用户的状态,修改提交函数:
const onSignUpPressed = async (data) => {
    console.log(data);
    try {
        const updatedUser = await isSignUp(email, password, displayName);
        // 手动更新Context中的用户状态,确保首页能拿到最新数据
        setCurrentUser(updatedUser);
        // 执行重定向到首页的操作
        navigation.navigate('Home');
    } catch (error) {
        console.log(error);
        switch(error.code) {
            case "auth/email-already-in-use" : alert("该邮箱已被注册");
            break;
        }
    }
}
  1. 确保首页从Auth Context读取用户信息
    如果首页之前是直接通过getAuth().currentUser获取数据,建议改为从Context中读取状态,因为Context状态会随手动更新实时变化,而currentUser可能需要重启或重新登录才会刷新。

内容的提问来源于stack exchange,提问作者Antoine Laurent

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 00:54:10