首页 > 解决方案 > 出现错误:对象作为 React 子对象无效

问题描述

issueList 数组元素的屏幕截图,它是一个对象。 问题列表数组

import React from 'react';

const IssueList = (props)=>{
    const issues = props.issueList.map((issue)=>{
        return (
            <div key={issue.id}>
                <span>
                    <p><strong>Issue Title: </strong>{issue.title}   </p>
                    <p>   <strong>Created By : </strong>{issue.user["login"]}</p>
                </span>   
                <p><strong>Assigned to: </strong>{issue.assignee}</p>
                <p><strong>Issue Description: </strong>{issue.body}</p>
            </div>
        )

    });

    return <div>{issues}</div>;
}

我正在尝试使用我的 issueList 对象数组中的一些信息来渲染一个 div。上面的代码产生以下错误:

Error: Objects are not valid as a React child (found: object with keys {login, id, node_id, avatar_url, gravatar_id, url, html_url, followers_url, following_url, gists_url, starred_url, subscriptions_url, organizations_url, repos_url, events_url, received_events_url, type, site_admin}). If you meant to render a collection of children, use an array instead.
    in p (at IssueList.js:12)
    in div (at IssueList.js:7)
    in div (at IssueList.js:19)

issueList 是一个对象数组

标签: node.jsreactjsjsxreact-component

解决方案


因此,您有一个issueList要呈现为组件列表的数组(比方说IssueList)。假设您的问题设置如下

issue = {
  id: "ID string",
  title: "Title",
  user: "User name",
  assignee: "Asignee name",
  body: "body string ..... "
}

您可以首先设置您的IssueList组件如下

const IssueList = ({ issueList }) => (
  <div>
  {
    issueList.map((issue) => (
      <div key={issue.id}>
        <span>
           <p><strong>Issue Title: </strong>{issue.title}   </p>
           <p>   <strong>Created By : </strong>{issue.user}</p>
        </span>
        <p><strong>Assigned to: </strong>{issue.assignee}</p>
        <p><strong>Issue Description: </strong>{issue.body}</p>
      </div>
    )
  }
  </div>
)

现在您可以在IssueList任何地方使用。


推荐阅读