React render: Objects are not valid as a React child

前端 未结 4 1700
自闭症患者
自闭症患者 2020-12-21 06:03

Please help me. I don\'t know why this piece of code doesn\'t work.

It gives me an error: \"Objects are not valid as a React child (found: object with keys {itemss})

相关标签:
4条回答
  • 2020-12-21 06:14

    You need to wrap items in JSX in your return statement:

    return (
        <React.Fragment>
            {items}
        </React.Fragment>
    )
    

    Your final return statement currently is not inside JSX. It's plain old JavaScript that is constructing an object like {items: items} thanks to enhanced object literals, which is why React is saying you are giving it an item with key items.

    0 讨论(0)
  • 2020-12-21 06:27
    return (
            {items} 
        )
    
    1. In the above line, you render the "items" list. You should render the "item" list which you have create from the map function of the "items" list.

    2. And you should be render it into an element.

      class ShopItem extends React.Component {

      render() { var items = [ { link: 'first link', title: 'Emery NEM XF', price: '$950' }, { link: 'second link', title: 'Emery NEM XF', price: '$950' }, { link: 'third link', title: 'Emery NEM XF', price: '$950' } ];

       const item = items.map((i) =>{
      
            return ( <h1>{i.title}</h1> )
      });
      
      return (
          <div>
          {item} 
          </div>
      )
      

      } }

    ReactDOM.render( , document.querySelector('#root'));

    0 讨论(0)
  • 2020-12-21 06:29

    The problem is because you return

    return (
            {items} 
        )
    

    which is an equivalent of return ({items: items}) ie. you are returning an object with key items and React doesn't expect objects for rendering. You could either write

       const items = items.map((i) =>{
          return ( <h1>{i.title}</h1> )
       });
    
       return items;
    

    or

         return items.map((i) =>{
            return ( <h1>{i.title}</h1> )
         });
    

    or

      const items = items.map((i) =>{
          return ( <h1>{i.title}</h1> )
       });
    
      return <React.Fragment>
            {items} 
        </React.Fragment>
    

    P.S. Note that the first two approaches will work from react v16.0.0 onwards while the last will work from v16.2 onwards.

    However if you are using a lower version, you would need to wrap the return element within a container like

        return (
            <div>{items}</div> 
        )
    
    0 讨论(0)
  • 2020-12-21 06:34

    here you go:

    return (
        <div>
            {items.map(i) => (
                <h1>{i.title}</h1>
            )}
        </div>
    )
    

    edit: in react, return/render can not have a structure like

    <h1>{i.title}</h1>
    <h1>{i.title}</h1>
    <h1>{i.title}</h1>
    

    you should wrap them in a <div> or another element. also you JS was wrong which I corrected

    0 讨论(0)
提交回复
热议问题