不变违规对象作为React子元素无效

时间:2019-02-04 10:55:23

标签: javascript reactjs

Objects are not valid as a React child (found: object with keys {id, title, category, stock, price}). If you meant to render a collection of children, use an array instead.
    in li (created by ListGroupItem)
    in ListGroupItem (at App.js:36)
    in ul (created by ListGroup)
    in ListGroup (at App.js:35)
    in div (at App.js:34)
    in App (at src/index.js:7)

此错误是什么意思?我怎么解决这个问题 我的渲染组件在这里:

render() {
    return (
      <div>
        <ListGroup>
          <ListGroupItem>{this.state.movies}</ListGroupItem>
          <ListGroupItem>Dapibus ac facilisis in</ListGroupItem>
          <ListGroupItem>Morbi leo risus</ListGroupItem>
          <ListGroupItem>Porta ac consectetur ac</ListGroupItem>
          <ListGroupItem>Vestibulum at eros</ListGroupItem>
        </ListGroup>
      </div>
    );
  }

2 个答案:

答案 0 :(得分:0)

JSX不支持对象。它支持数组或字符串。

因此,请使用Object.keys或Object.entries返回键和值的数组。

映射整个数组以在UI中呈现元素

render() {
    return (
      <div>
        <ListGroup>
          <ListGroupItem>
          {
          Object.entries(this.state.movies).map(([key, value]) => (
           <>
           {key}
           {value}
           </> 
            ));
            }

          </ListGroupItem>
          <ListGroupItem>Dapibus ac facilisis in</ListGroupItem>
          <ListGroupItem>Morbi leo risus</ListGroupItem>
          <ListGroupItem>Porta ac consectetur ac</ListGroupItem>
          <ListGroupItem>Vestibulum at eros</ListGroupItem>
        </ListGroup>
      </div>
    );
  }

答案 1 :(得分:0)

<ListGroupItem>{this.state.movies}</ListGroupItem>

错误是因为此行。您能否更具体地说明要实现的目标?如果要直接打印对象,请使用

<ListGroupItem>{JSON.stringify(this.state.movies)}</ListGroupItem>