[英]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.