[英]ReactJS Error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead
[英]Cannot display data in ReactJS. Error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead
我正在尝试显示来自后端的数据,但出现错误:错误:对象作为 React 子项无效(找到:object,键为 {id、price、descr、link、sqf})。 如果您打算渲染子集合,请改用数组。
我一直在寻找解决方案,我遇到了。map 但它不起作用再次引发错误。
import React, { useState, useEffect } from 'react';
import ArticleService from '../services/articles';
const Dashboard = () => {
const [content, setContent] = useState('');
useEffect(() => {
ArticleService.articles().then(
(response) => {
setContent(response.data);
},
(error) => {
const _content =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
setContent(_content);
}
);
}, []);
console.log(content);
return (
<div className='container'>
<h3>{content}</h3>
</div>
);
};
export default Dashboard;
如您所见,我定期获取内容,只是无法在仪表板页面上显示。 当我尝试{content.price}
时,它消除了一个错误,但仍然没有显示任何内容。 有什么解决办法吗???
根据您的日志, content
是一个对象数组,因此您希望将数组 map 转换为有效的 JSX,例如,如果您想在div
元素中呈现:
<div className="container">
<h3>
{content?.map((item) => (
<div key={item.id}>
<div>{item.price}</div>
<div>{item.descr}</div>
</div>
))}
</h3>
</div>
此外,初始的 state 应该是一个空数组: useState([])
来匹配预期的数据:
const Dashboard = () => {
const [content, setContent] = useState([]);
...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.