【问题标题】:Objects are not valid as a React child (found: object with keys {<key>}). If you meant to render a collection of children, use an array instead对象作为 React 子对象无效(找到:带有键 {<key>} 的对象)。如果您打算渲染一组孩子,请改用数组
【发布时间】:2019-12-03 18:53:49
【问题描述】:

我想制作一个包含 Material-ui 网格的组件。

这里有一个codeandbox:codesanbox

这是容器组件。 AllCards.js

// All the required imports here

const exer = [
  {
    imageurl: "https://media1.giphy.com/media/26tPtg8M3i6DPSSt2/200w.gif",
    imagealt: "react-gif",
    title: "Elongacion de columna",
    body: "Este es un ejercicio que sirve para estirar los lumbares.",
    firstButtonText: "Ver",
    secondButtonText: "Ayuda"
  },
  {
    imageurl: "https://media1.giphy.com/media/26tPtg8M3i6DPSSt2/200w.gif",
    imagealt: "react-gif",
    title: "Elongacion de cuadriceps",
    body: "Este es un ejercicio que sirve para estirar los cuadriceps.",
    firstButtonText: "Ver"
  }
];

function AllCards() {
  const [exercises, setExercises] = useState(null);

  useEffect(() => {
    setExercises(exer);
  }, [exercises]);

  let ret = exercises ? <CardGrid cards={exercises} /> : null;
  return ret;
}

export default AllCards;

这是 CardGrid.js 组件

const CardGrid = props => {
  const classes = useStyles();
  const { cards } = props;

  return (
    <div className={classes.root}>
      <Grid container spacing={3} justify="space-evenly" alignItems="center">
        {cards.map((currentCard, ind) => (
          <Grid key={ind} item xs>
            <CardItem card={currentCard} />
          </Grid>
        ))}
      </Grid>
    </div>
  );
};

我的 CardItem.js 组件

const CardItem = props => {

  let ret = null;       
  if (props.card) {
    console.log("ITEM PROPS", props);
    ret = ( <Card . . . )
  // return { ret };     <-- THIS IS WRONG
     return ret          <-- SHOLD BE LIKE THIS
};

我有以下错误

Error: Objects are not valid as a React child (found: object with keys {card}). If you meant to render a collection of children, use an array instead.
    in CardItem (at CardGrid.js:49)

已解决:

在 CardItem.js 中我返回 { ret }

应该是return ret

【问题讨论】:

  • 看起来你正在改变CardGrid 中的excercise 属性,最初的属性是props.cards,但后来它改变了props.card

标签: reactjs react-props


【解决方案1】:

在您的沙盒示例中,您在 CardGrid.js 中的代码顶部有 import CardItem from "./CardGrid";。我假设你想说import CardItem from "./CardItem";

然后,我相信您的组件需要能够保存 ForwardRefs,本指南将帮助您。 https://material-ui.com/guides/composition/

【讨论】:

    【解决方案2】:

    正如 Thomas 所指出的,您从错误的文件中导入了 CardItem。此外,在 CardItem 内部,您使用了一个名为 card 的道具,但还创建了一个名为 card 的新变量来返回组件,这会导致命名冲突并尝试渲染一个不允许的对象。

    如果您更改变量名,它似乎可以工作。

    分叉here

    【讨论】:

    • 嗨,克里斯,我打开了你的 codesanbox,但它不工作。我更新了我的问题以显示我现在遇到的错误。
    • 它可能没有保存,但现在似乎可以工作了。
    猜你喜欢
    • 2020-10-18
    • 2021-11-18
    • 2019-10-12
    • 2021-04-19
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多