【问题标题】:Error: Objects are not valid as a React child If you meant to render a collection of children, use an array instead Im not sure where I am going wrong错误:对象作为 React 子级无效如果您打算渲染一组子级,请改用数组我不知道哪里出错
【发布时间】:2021-06-15 10:20:22
【问题描述】:

我收到错误为-错误:对象作为 React 子项无效(找到:带有键 {itemname、imageUrl、subitems} 的对象)。如果您打算渲染一组子项,请改用数组。

这是我的代码:

import React from 'react';
import reactDom from 'react-dom';
import DATA from '../../components/data/data';
import Itemcard from './homepage-directory';

 class Homepage extends React.Component  {
     constructor(){
         super();
         this.state={
             menu:DATA
         };
     }
render(){
  
    
    return(
        <div className = 'homepage' >
            {
                this.state.menu.map(
                    ({id, ...otherprops}) => <Itemcard key={id} {...otherprops}/>
                )
            }
            <h1>lololol</h1>

        </div>
    )
}
 }
 export default Homepage;

这是另一个组件:

import react from 'react';
import './homepage-directory.styles.scss';

const Itemcard = (itemname, key, imgUrl ) =>(
    <div className='itemcard'
        style={{
            backgroundImage: `url(${imgUrl})` }}
    >
        <div>
            <h2> {itemname} </h2>
       </div>
    </div>
)

export default Itemcard;

这是我的数据-

 const DATA = [
     {  id:1,
        itemname:'brownie',
        imageUrl:'https://i.ibb.co/XJ53VVd/nutella-brownie.jpg',
        subitems:[]
         

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    因为你使用了错误的道具。你需要像这样更新你的代码:

    const Itemcard = ({ itemname, key, imgUrl }) =>(...)
    

    【讨论】:

      【解决方案2】:

      它在抱怨,因为你没有以正确的方式解构它。

      1. 在函数定义时对其进行解构。可以在定义参数时实现。如果您有很多道具,则不建议使用此方法,因为它会降低可读性,但在您的情况下它很好。

        const Itemcard = ({ itemname, key, imgUrl }) =>{ ...component
        }

      2. 如果您发现这更复杂,只需在需要时使用 props 作为参数和组件内部的结构

      const Itemcard = (props) => {
        const { itemname, key, imgUrl, rest } = props;
      };
      
      1. 普通的旧 props.yourProps

      【讨论】:

        猜你喜欢
        • 2019-06-14
        • 2020-06-24
        • 2021-01-02
        • 2020-12-22
        • 2021-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多