【发布时间】: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.title 和 size 都传递到 addToCart() 中?
【问题讨论】:
标签: javascript json reactjs graphql gatsby