react报错,Objects are not valid as a React child (found: object with keys {xxx})

172 阅读1分钟

错误展示

Objects are not valid as a React child (found: object with keys {xxx}). If you meant to render a collection of children, use an array instead

image.png

产生以上错误的原因是,在jsx语法中错误的渲染了对象数据,在 react 语法设计里,数组和基本数据类型可以直接插入jsx渲染,但是不可以直接插入对象进行渲染。

const obj = {
    Android : <span>test</span>,
}
// ...
return (
   <div>{obj}</div> {/* 错误的写法 */}
)

例如以上的写法,不能直接将对象插入到jsx中渲染视图,如果要渲染对象数据应该使用插入对象属性的方式渲染

解决方法

将对象进行属性提取,可以将对象转成数组的方式渲染数据

<div>{Object.entries(obj)[1]}</div>

对于数据的渲染,应该避免将对象直接插入到jsx中{obj},如果有需要展示对象结构,可以通过 JSON.stringify将对象序列化后进行插入渲染