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

React报错:Objects are not valid as a React child 排查求助

解决React报错:Objects are not valid as a React child

核心错误原因

你的SingleRecord组件参数写法不符合React规范,导致渲染了对象类型的内容,触发报错。

React函数组件的第一个参数是props对象,而非单独的属性参数。你当前的写法中,firstName实际上是整个props对象,age是第二个参数(上下文),渲染{firstName}时相当于直接渲染一个对象,这违反了React只能渲染原始类型或合法React元素的规则。


修复步骤

1. 修正SingleRecord组件的参数接收方式

将组件改为解构props对象,或者通过props访问属性:

// 方式1:解构props(推荐)
const SingleRecord = ({ firstName, age }) => {    
    return (
    <li className="singe-record">
        {firstName} is {age} years old.
    </li>
    );
}

export default SingleRecord;

或者:

// 方式2:直接接收props对象
const SingleRecord = (props) => {    
    return (
    <li className="singe-record">
        {props.firstName} is {props.age} years old.
    </li>
    );
}

export default SingleRecord;

2. 优化Display组件的数据处理逻辑

  • 将dataArray移到fetchRecords内部,避免组件渲染时重复创建空数组引发的闭包问题
  • 直接用map生成新数组,替代循环push的写法
  • 给useState设置初始空数组,简化空值判断

修改后的核心代码片段:

function Display() {
    // 初始值设为空数组
    const [records, setRecords] = useState([]);

    const fetchRecords = () => {
        fetch('http://localhost:3001/users')
        .then(async response => {
            const isJson = await response.headers.get('content-type')?.includes('application/json');           
            const data = isJson ? await response.json() : null;

            // 直接用map生成目标数组
            const dataArray = data.map(elem => ({
                _id: elem._id, 
                firstName: elem.firstName,
                age: elem.age
            }));
            setRecords(dataArray);

            if (!response.ok) {
                const error = (data && data.message) || response.status;
                return Promise.reject(error);
            }
        })
        .catch(error => {
            console.error('There was an error!', error);
        });
    }

    // ...其余代码不变
}

3. 给列表项添加唯一key

React要求列表渲染时每个子项必须有唯一的key属性,避免性能问题和警告:

const LI = records.map(elem => {
    // 使用MongoDB返回的_id作为唯一key
    return <li key={elem._id}><SingleRecord firstName={elem.firstName} age={elem.age} /></li>
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:35:19