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

React渲染报错:Objects are not valid as a React child及Firebase登录错误展示求助

问题解决:登录错误码无法展示及React渲染报错

问题原因

  • 组件参数接收错误:你把组件的props写成了errorCode,但React组件的props是一个对象,这里的errorCode实际是空的props对象,渲染时React尝试把这个对象当作子元素,直接触发Objects are not valid as a React child报错。
  • 错误状态管理不当:你用errorText布尔值标记是否有错误,但没有存储具体的错误码,就算标记为true,也无法获取正确的错误内容。

修改方案及代码

调整组件参数、优化状态管理,直接在组件内部存储并展示错误码:

import { signInWithEmailAndPassword } from 'firebase/auth';
import React, { useState } from 'react';
import auth from '../../Firebase/firebase';

// 修正props接收方式,组件内部处理错误,无需外部传入errorCode
const SignIn = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    // 用state存储错误码,初始值为null表示无错误
    const [errorCode, setErrorCode] = useState(null);

    const signIn = (e) => {
        e.preventDefault();
        // 每次登录前清空之前的错误记录
        setErrorCode(null);
        signInWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                console.log(userCredential);
            })
            .catch((error) => {
                const code = error.code;
                console.log(code);
                // 将获取到的错误码存入state
                setErrorCode(code);
            });
    };

    return (
        <div>
            <form onSubmit={signIn}>
                <h1>Hey, Log In</h1>
                <input
                    type='email'
                    placeholder='enter email'
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                />
                <input
                    type='password'
                    placeholder='enter pass'
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                />
                {/* 存在错误码时才渲染错误提示 */}
                {errorCode && <div>{errorCode}</div>}
                <button type='submit'>Push to login</button>
            </form>
        </div>
    );
};

export default SignIn;

关键修改说明

  1. 移除组件参数中的errorCode,因为错误是组件内部登录逻辑产生的,不需要外部传入。
  2. 替换errorText布尔状态为errorCode状态,专门存储具体的错误码,初始值null表示无错误。
  3. 登录前清空错误状态,避免上次错误残留。
  4. 捕获错误时直接将error.code存入状态,渲染时判断状态是否存在,存在则展示错误码,彻底避免渲染对象的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:30:42