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

React表单提交Firebase时onSubmit内user.uid未定义问题排查

问题原因及解决办法

核心问题是变量命名冲突:你给onSubmit函数的参数起名叫user,但这个参数其实是react-hook-form传递的表单输入数据(你的表单里只有提交按钮,所以这个user是空对象),它覆盖了外部从useAuth获取的用户对象,导致函数内部的user.uid自然是undefined。

解决步骤:

  • 把onSubmit的参数名改成和外部user不冲突的名字,比如formData
  • 在函数内部直接使用从useAuth拿到的user对象来获取uid
  • 保留user存在性判断,避免未登录状态下执行数据库操作出错

修改后的代码示例:

import React from "react";
import { useForm } from "react-hook-form";
import { db, auth } from '../firebase/firebaseInit'
import {useAuth} from '../components/AuthContextProvider'
import { collection, setDoc, doc } from '@firebase/firestore'
import Logout from '../components/Logout'

type Inputs = {
  example: string,
  exampleRequired: string,
};

export default function LoggedIn() {
    const { user  } = useAuth()
    const { register, handleSubmit, watch, formState: { errors } } = useForm<Inputs>();
    console.log(user.uid, 'this uid is not undefined')
    // add their kid to the kids collection
    const onSubmit = async (formData: any) => {
        // 使用外部的user对象,不再用参数里的
        if (user) {
            console.log(user.uid, 'uid正常获取')
            const userRef = doc(db, `kids/${user.uid}`);
            await setDoc(userRef, {
                parent: user.displayName,
                email: user.email,
                uid: user.uid,
                name: 'Charlie',
            });
        }
    }

    return (
    <div>
        <Logout />
        <form onSubmit={handleSubmit(onSubmit)}>
        <input type="submit" />
    </form>
    </div>
    );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 03:54:29