Error: Objects are not valid as a React child. When i use a child property
Error: Objects are not valid as a React child. When i use a child property
我在我的 React 应用程序中遇到此错误:
Error: Objects are not valid as a React child. If you meant to render
a collection of children, use an array instead.
在我的 React 组件中,我调用了一个 API 并得到了一个 Json 的响应,如下所示:
{
title: "myTitle",
description: "My Description",
...
state: {
id: 1,
stateTitle: "active"
},
}
我可以使用所有属性,但不能使用子对象中的 属性。
const myComponent = () => {
...useEffect...API call...
return (
<div>
<h1>{data.title}</h1> <<--- This works fine...
<span>{data.state.stateTitle}</span> <<--- here i am getting the error
</div>
);
}
export default myComponent;
我尝试用 JSON.stringify() 方法显示值,这也很好用。
<span>{JSON.stringify(data.state)}</span> // result: {"id":i,"stateTitle":"active"}
或者用console.log(data.state.stateTitle)打印;按预期工作..
为什么我在尝试打印子元素的值时出现此错误。
我相信您已经使用默认值初始化了 data
,这可能在渲染部分失败了。该组件在调用 API 之前使用默认值 data
呈现除法。一旦收到 API 响应,组件将获得 re-rendered 和获取的响应。
我在我的 React 应用程序中遇到此错误:
Error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead.
在我的 React 组件中,我调用了一个 API 并得到了一个 Json 的响应,如下所示:
{
title: "myTitle",
description: "My Description",
...
state: {
id: 1,
stateTitle: "active"
},
}
我可以使用所有属性,但不能使用子对象中的 属性。
const myComponent = () => {
...useEffect...API call...
return (
<div>
<h1>{data.title}</h1> <<--- This works fine...
<span>{data.state.stateTitle}</span> <<--- here i am getting the error
</div>
);
}
export default myComponent;
我尝试用 JSON.stringify() 方法显示值,这也很好用。
<span>{JSON.stringify(data.state)}</span> // result: {"id":i,"stateTitle":"active"}
或者用console.log(data.state.stateTitle)打印;按预期工作..
为什么我在尝试打印子元素的值时出现此错误。
我相信您已经使用默认值初始化了 data
,这可能在渲染部分失败了。该组件在调用 API 之前使用默认值 data
呈现除法。一旦收到 API 响应,组件将获得 re-rendered 和获取的响应。