【问题标题】:Structuring and retrieving JSON object (an image) with multiple sizes结构化和检索具有多种大小的 JSON 对象(图像)
【发布时间】:2021-08-19 05:08:06
【问题描述】:

这就是我目前的 JSON 数据结构:

[
  {
    "slug": "image-1",
    "title": "Image 1",
    "img": "./images/folder1/Image-1.jpg",
    "sizes": [
      {
        "title": "Image 1",
        "size": "Large",
        "price": "$1799",
      },
      {
        "title": "Image 1",
        "size": "Medium",
        "price": "$1299",
      },
      {
        "title": "Image 1",
        "size": "Small",
        "price": "$799",
      }
    ]
  },
  {
    "slug": "image-2",
    ...
    ...
    ...
  }
]

我正在映射尺寸并在单击“添加”按钮时调用 addToCart(size)。

模板.js:

const details = data.Json
const { addToCart } = useContext(GlobalContext)

// <h1>{details.title}</h1>
// <img src={details.img} />
details.sizes.map((size, index) => {
  return (
    <h2>{size.size}</h2>
    <h2>{size.price}</h2>
    <button onClick={() => addToCart(size)}>
      Add
    </button>
  )
})

GlobalState.js:

function addToCart(cartItem) {
  dispatch({
    type: "ADD_TO_CART",
    payload: cartItem,
  })
}

AppReducer.js:

export default (state, action) => {
  switch (action.type) {
    case "ADD_TO_CART":
      return {
        ...state,
        cartItems: [...state.cartItems, action.payload],
      }

单击“添加”按钮后,购物车中将显示以下内容:

标题大小价格 图片 1 中 1299 美元

CartItem.js:

export const CartItem = ({ cartItem }) => {
  return (
<Item>
  <p>{cartItem.title}</p>
  <p>{cartItem.size}</p>
  <p>{cartItem.price}</p>
</Item>
  )
}

现在这行得通;但是,我想从每个尺寸中删除标题,以便我的 JSON 数据如下所示:

[
  {
    "slug": "image-1",
    "title": "Image 1",
    "img": "./images/folder1/Image-1.jpg",
    "sizes": [
      {
        "size": "Large",
        "price": "$1799",
      },
      {
        "size": "Medium",
        "price": "$1299",
      },
      {
        "size": "Small",
        "price": "$799",
      }
    ]
  },
  {
    "slug": "image-2",
    ...
    ...
    ...
  }
]

我怎样才能将 details.titlesize 都传递到 addToCart() 中?

【问题讨论】:

    标签: javascript json reactjs graphql gatsby


    【解决方案1】:

    您可以将组件范围内的details.title 值代理到一个新对象中,其中包含大小属性。

    // <h1>{details.title}</h1>
    // <img src={details.img} />
    details.sizes.map((size, index) => {
      return (
        <h2>{size.size}</h2>
        <h2>{size.price}</h2>
        <button
          onClick={() => addToCart({
            title: details.title,
            ...size,
          })}
        >
          Add
        </button>
      )
    })
    

    【讨论】:

      猜你喜欢
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      相关资源
      最近更新 更多