【问题标题】:pushing an object to an array in state React ERROR(objects are not valid...)将对象推送到状态为 React ERROR 的数组(对象无效...)
【发布时间】:2020-06-01 01:12:39
【问题描述】:

我是新手,我如何才能在状态下正确地将对象添加到数组中,我收到错误消息:“错误:对象作为 React 子项无效(找到:带有键的对象 {product })。如果您打算渲染一组子项,请改用数组。”我能做的是每次单击按钮时将对象推入列表?

import React, { useContext, useState } from 'react'
import {SnacksContext} from './Snacks'
import AddtoCart from './AddToCart'
const SnackItem=()=>{
    const [snacks,setSnack]=useContext(SnacksContext)
    const [list,setList]=useState([])
    return(
        <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(200px,1fr))"}}>
            {snacks.map(i=>(
                <div>
                     <img src={i.picture}></img>
                      <h1>{i.product}</h1>
                      <h2>{i.price}</h2>
                      <button onClick={()=>setList(list=>[...list,i])}>buy</button>
                  </div>
            ))}

        </div>
    )

【问题讨论】:

  • 你能在snacks数组里面加上值吗?

标签: reactjs


【解决方案1】:
Objects are not valid as a React child (found: object with keys {product}).

由于错误,很明显snacks 是一个对象数组,其中product 是一个对象的键。您正在尝试渲染一个对象 - 像这样 - &lt;h1&gt;{i.product}&lt;/h1&gt;

所以查看i.product 的属性并相应地渲染它。例如:i.product.title

                  <div>
                     <img src={i.picture}></img>
                      <h1>{i.product.title}</h1> //<---- see here
                      <h2>{i.price}</h2>
                      <button onClick={()=>setList(list=>[...list,i])}>buy</button>
                  </div>

【讨论】:

    猜你喜欢
    • 2017-06-05
    • 2021-11-06
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多