React : Invariant Violation: Objects are not valid as a React child

Jon*_*Jon 3 javascript ecmascript-6 reactjs

我正在研究 ReactJS 搜索过滤器,目前我遇到一个问题,当我输入匹配输入应用程序崩溃并出现此错误时,Objects are not valid as a React child (found: object with keys {id, companyName, account, venueCode, openDate, website, primaryPhone, emailAddress, description, firstName, lastName, active, title, department, officePhone, mobilePhone, tenantId, hidden, deleted, parentId}). If you meant to render a collection of children, use an array instead.请有人帮助我如何解决此问题。我是初学者,没有太多的知识来解决这个问题。当我输入一些匹配输入时,应用程序第一次渲染成功,它给我一个错误。

代码

        class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Item: 5,
      skip: 0
    }

    this.handleClick = this.handleClick.bind(this);
  }

  urlParams() {
    return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
  }

  handleClick() {
    this.setState({skip: this.state.skip + 1})
  }

  render() {
    return (
      <div>
        <a href={this.urlParams()}>Example link</a>
        <pre>{this.urlParams()}</pre>
        <button onClick={this.handleClick}>Change link</button>
      </div>
    )
  }
}


ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))
Run Code Online (Sandbox Code Playgroud)

Asl*_*ace 8

当您尝试渲染对象而不是 JSX 时会发生这种情况。做出我最有根据的猜测,我认为这条线是问题所在:

let filtered=this.state.data.filter((item)=>{
      return item.companyName.indexOf(keyword) > -1
    });
Run Code Online (Sandbox Code Playgroud)

Filtered 似乎是一个对象数组,而不是 JSX,所以在 render 方法中:

{this.state.filtered.length === 0 ? dataRender : this.state.filtered}
Run Code Online (Sandbox Code Playgroud)

可能会尝试渲染过滤的对象,而不是 JSX。

要解决此问题,请尝试添加以下内容:

const filterRender=this.state.filtered.map((dataItem)=>(
  <Table.Row key={dataItem.id}>
  <Table.Cell>{dataItem.companyName}</Table.Cell>
  <Table.Cell>{dataItem.primaryPhone}</Table.Cell>
  <Table.Cell>{dataItem.emailAddress}</Table.Cell>
  <Table.Cell>{dataItem.venueCode}</Table.Cell>
  <Table.Cell>{dataItem.account}</Table.Cell>
  <Table.Cell>{dataItem.openDate}</Table.Cell>
  <Table.Cell>{dataItem.website}</Table.Cell>
  <Table.Cell>{dataItem.description}</Table.Cell>
</Table.Row>
))
Run Code Online (Sandbox Code Playgroud)

并将其更改为:

{this.state.filtered.length === 0 ? dataRender : filterRender}
Run Code Online (Sandbox Code Playgroud)

正如@jsdeveloper 在下面指出的那样,制定一种renderRow方法来处理这个问题是个好主意。