【问题标题】:How to fix Objects are not valid as a React child如何修复对象作为 React 子项无效
【发布时间】:2019-04-12 16:24:45
【问题描述】:

我正在尝试呈现购物车中的商品列表。项目列表作为道具从我的父组件传递。我正在调用 mapCartItemsToItems 但它没有呈现并表明

“对象作为 React 子对象无效(发现:对象的键为 {childKey, header, meta, extra})。如果您要渲染一组子对象,请改用数组。”

const mapCartItemsToItems = items =>
    items.map(({ id, product_id, name, quantity, meta }) => {
      const price = meta.display_price.with_tax.unit.formatted || null

      return {
        childKey: id,
        header: (
          <Link href={`/product?id=${product_id}`} passHref>
            <div>{name}</div>
          </Link>
        ),
        meta: `${quantity}x ${price}`,
        extra: <button onClick={() => removeFromCart(id)}>Remove</button>
      }
    })
return <div>{mapCartItemsToItems(items)}</div>

【问题讨论】:

  • return {你要返回一个对象?
  • 另外,它应该返回 JSX,而不是 javascript 对象。

标签: javascript arrays reactjs object next.js


【解决方案1】:

正如错误所说,您正在尝试将简单对象用作元素中的子对象。你不能在 React 中做到这一点。

如果您想在您生成的列表中使用childKeyheadermetaextra,您需要在map 回调中创建一个元素结构,而不是一个普通对象。 (或者稍后再使用第二个map,但是...)

例如(当然,您必须调整此结构以满足您的需要):

const mapCartItemsToItems = items =>
    items.map(({ id, product_id, name, quantity, meta }) => {
        const price = meta.display_price.with_tax.unit.formatted || null

        return (
            <div key={id}>
                <Link href={`/product?id=${product_id}`} passHref>
                    <div>{name}</div>
                </Link>
                {quantity}x {price}
                <button onClick={() => removeFromCart(id)}>Remove</button>
            </div>
        )
    })
return <div>{mapCartItemsToItems(items)}</div>

【讨论】:

  • 非常感谢!你说得非常清楚,让我免于沮丧!
猜你喜欢
  • 2019-07-10
  • 1970-01-01
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 2021-12-02
  • 1970-01-01
  • 2021-02-24
相关资源
最近更新 更多