React render: Objects are not valid as a React child

前端 未结 4 1710
自闭症患者
自闭症患者 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: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 ( 

    {i.title}

    ) }); return items;

    or

         return items.map((i) =>{
            return ( 

    {i.title}

    ) });

    or

      const items = items.map((i) =>{
          return ( 

    {i.title}

    ) }); return {items}

    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 (
            
    {items}
    )

提交回复
热议问题