【问题标题】:Getting error Objects are not valid as a React child获取错误对象作为 React 子对象无效
【发布时间】: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;

【问题讨论】:

  • 你有两对花括号,这就像小时候传递一个对象一样。删除一对:&lt;div className="App"&gt;{blogCards}&lt;/div&gt;
  • .map() 返回新数组,因此您的 blogCards 是一个数组。您需要在侧返回(渲染)语句中使用.map()

标签: reactjs


【解决方案1】:

正如@zsolt-meszaros 在 cmets 中提到的,问题出在这段代码上:

    <div className="App">
      {
        {blogCards}
      }
    </div>

它们自己的行上的大括号离开 JSX 模式并进入 JavaScript 模式。在 JavaScript 中,{blogCards} 等价于 {"blogCards": blogCards},即,创建一个具有一个属性的对象,其键为 "blogCards",值等于 blogCards 变量。因此 React 得到一个对象并抱怨。

您只需将代码更改为:

    <div className="App">
      {blogCards}
    </div>

【讨论】:

    【解决方案2】:

       <div className="App">
          {
            blogCards
          }
        </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      • 2016-10-26
      • 2021-08-05
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      相关资源
      最近更新 更多