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

React Native Redux应用中Firebase无法写入用户姓名至数据库

解决Firebase注册后无法写入用户数据的问题

我帮你排查下这个问题,从你的代码和规则来看,主要有几个可能的原因,咱们一步步来解决:

1. 确认Firebase Auth返回的用户对象结构

你当前的代码里直接用了user.uid,但最新版本的Firebase Auth中,createUserWithEmailAndPassword返回的是UserCredential对象,而不是直接的User实例。用户的真实信息(包括uid)需要从userCredential.user里获取。如果你的Firebase版本较新,直接用user.uid会得到undefined,导致数据被写入到users/undefined这个隐藏路径里,自然在数据库里看不到。

2. 给数据库写入操作添加错误捕获

你的set()方法后面没有加catch块,即使写入失败(比如权限被拒、路径错误)也看不到具体错误信息,这会让你很难定位问题。

3. 验证规则与用户认证状态匹配

你的规则是正确的,但要确保写入时用户已经完成认证,且auth.uid和路径中的$uid完全一致。

修改后的代码示例

export const signUpUser = ({ firstname = "", lastname = "", email, password }) => (dispatch) => {
  dispatch({ type: SIGN_UP_REQUEST });
  firebase.auth().createUserWithEmailAndPassword(email, password)
    .then((userCredential) => {
      // 从UserCredential中取出真实的用户对象
      const user = userCredential.user;
      // 先在控制台打印uid,确认是否正确
      console.log("当前用户UID:", user.uid);
      
      firebase.database().ref(`users/${user.uid}`)
        .set({ 
          firstname: 'AJINKYA', 
          lastname: 'AJINKYA' 
        })
        .then(() => {
          dispatch({ type: SIGN_UP_SUCCESS, payload: user });
          Actions.home();
        })
        // 添加错误捕获,打印数据库写入失败的具体原因
        .catch((dbError) => {
          console.error("数据库写入错误:", dbError);
          dispatch({ type: SIGN_UP_FAILURE, payload: "保存用户信息失败" });
        });
    })
    .catch((authError) => {
      dispatch({ type: SIGN_UP_FAILURE, payload: authFailMessage(authError.code) });
    });
};

额外排查步骤

  • 临时测试规则:可以去Firebase控制台的「实时数据库」→「规则」页面,暂时将users/$uid的.write权限改成true,测试是否能成功写入。如果能写入,说明之前的权限规则因为uid不匹配被触发了;如果还是不能,那就是代码里的路径或用户对象问题。
  • 检查Firebase版本:确认你使用的Firebase Auth版本对应的API是否正确,避免因版本差异导致的对象结构不匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:23:38