如何修复对象作为 React 子项无效
How to fix Objects are not valid as a React child
我正在尝试呈现购物车中的项目列表。项目列表作为道具从我的父组件传递。我正在调用 mapCartItemsToItems 但它不呈现并指示
"Objects are not valid as a React child (found: object with keys {childKey, header, meta, extra}). If you meant to render a collection of children, use an array instead."
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>
如错误所述,您正在尝试将简单对象用作元素中的子对象。你不能在 React 中这样做。
如果您想在您生成的列表中使用 childKey
和 header
以及 meta
和 extra
,您需要在您的列表中创建一个元素结构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>
我正在尝试呈现购物车中的项目列表。项目列表作为道具从我的父组件传递。我正在调用 mapCartItemsToItems 但它不呈现并指示
"Objects are not valid as a React child (found: object with keys {childKey, header, meta, extra}). If you meant to render a collection of children, use an array instead."
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>
如错误所述,您正在尝试将简单对象用作元素中的子对象。你不能在 React 中这样做。
如果您想在您生成的列表中使用 childKey
和 header
以及 meta
和 extra
,您需要在您的列表中创建一个元素结构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>