【发布时间】:2021-08-11 15:33:28
【问题描述】:
我正在学习 react.js。我正在运行 App.js,但出现错误:- × 错误:对象作为 React 子对象无效(找到:带有键 {blogCards} 的对象)。如果您打算渲染一组子项,请改用数组
谁能告诉我为什么会出现这个错误,因为我是 react.js 的新手
import logo from './logo.svg';
import './App.css';
import React from 'react';
function App() {
const blogArr = [
{
id : 1,
title: 'Blog Title 1',
description : 'Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor'
},
{
id : 2,
title: 'Blog Title 2',
description : 'Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor'
},
{
id : 3,
title: 'Blog Title 3',
description : 'Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor'
}]
const blogCards = blogArr.map((item,pos) => {
console.log(item)
return (
<div className="BlogCard" key={pos}>
<h3>{item.title}</h3>
<p>{item.description}</p>
</div>
);
})
return (
<div className="App">
{
{blogCards}
}
</div>
);
}
export default App;
【问题讨论】:
-
你有两对花括号,这就像小时候传递一个对象一样。删除一对:
<div className="App">{blogCards}</div> -
.map()返回新数组,因此您的blogCards是一个数组。您需要在侧返回(渲染)语句中使用.map()
标签: reactjs