简体   繁体   中英

How to fix Objects are not valid as a React child

I'm trying to render a list of items in a cart. The list of items are passed as a props from my parent component. I'm calling mapCartItemsToItems but it doesn't render and indicate that

"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>

As the error says, you're trying to use simple objects as children in an element. You can't do that in React.

If you want to use childKey and header and meta and extra in the list you're producing, you need to create an element structure in your map callback rather than a plain object. (Or use a second map later to do it, but...)

For instance (but of course, you'll have to adjust this structure to suit your needs):

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM