开发者问题收集

子组件从对象 prop 数组接收“未定义”

2023-01-07
424

我有一个父组件,它有一个对象状态数组,此状态正在传递给子组件。当我收到此 prop 和 console.log 时,返回未定义。

父组件

import { useState } from "react";

import Children from './Children'

import cardsData from "../cardsData";

const Parent = () => {
 
  const [cards, setCards] = useState(cardsData); // set cardsData in a state

  return (
    <div className='flex flex-col w-full  my-4 gap-4 rounded-full md:grid grid-cols-4 md:grid-row-3'>
        <Children
          cards={cards}
        />
    </div>
  )
}

export default Parent

子组件

const Children = ({ cards }) => {
  console.log({cards});

  return (
    <div className="bg-white w-full h-60 md:col-span-2 rounded-lg">
      {cards[0].title}
    </div>
  );
};

export default CardSpanCol2;

我的数据

const cardsData = [
        {
            id:1,
            type: "about",
            title: "Gabriel Barros",
            subTitle: "Web Development",
            text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the",
        },{
            id:2,
            type: "about",
            picture: "./assets/me.jpg"
        },{
            id:3,
            type: "media",
            title:"Twitter"
        }
    ]


export default cardsData;

CONSOLE.LOG: 在此处输入图片描述

错误:TypeError:无法读取未定义的属性

2个回答

Children 组件出错,需要将基本字符串更改为“export default Children;”

AndreyDerets
2023-01-07

当您想要传递一个对象数组时,您可以尝试以下操作:

const Children = ( cards ) => {
   // notice the missing curly brackets
   console.log(cards)
   //your other code

不幸的是,我仍在寻找解释,但到目前为止这对我有用。

Mila
2023-05-18