【发布时间】:2019-09-22 13:35:43
【问题描述】:
我有一个 REACT JS 客户端,我想使用 push 方法将 购物车项目 保存在 localStorage 中。我有一个 AddtoCart 函数,它将被点击的产品的产品详细信息数组推送到 localStorage JSON 对象 CartObj。
但我想要的是将 localStorage 的整个 CartObj 采用 JSON 对象格式,其中产品根据它们的 CompanyNames 进行分组(而不仅仅是简单的字符串)。
当我点击“AddtoCart”按钮时,我会以这种格式发送一个产品详细信息:
{
"SparePartID":"45",
"Name":"Lights",
"Price":"2300",
"VendorID": "48",
"CompanyName": "Master Automotives",
"Qty": 1,
"TotalPrice": "4500"
}
我想要的是 push 在 CartObj JSON 对象 中的 localStorage 中的上述项目(CartObj 当前为空)。并且每当单击任何项目时,其数据都会被推送到相同的 CartObj。但是我想在我的 localStroage CartObj 中获得以下格式的数据,之后将一些项目推入其中。 (按公司名称分组的项目)。
{
"records": {
"Master Automotives": [
{
"SparePartID": "43",
"Name": "Oil and Lubricants",
"Price": "4500",
"VendorID": "48",
"CompanyName": "Master Automotives",
"Qty": 1,
"TotalPrice": "4500"
},
{
"SparePartID": "45",
"Name": "Lights",
"Price": "2300",
"VendorID": "48",
"CompanyName": "Master Automotives",
"Qty": 1,
"TotalPrice": "2300"
}
],
"Repair Solutions": [
{
"SparePartID": "47",
"Name": "Steering Wheel",
"Price": "1500",
"VendorID": "60",
"CompanyName": "Repair Solutions",
"Qty": 1,
"TotalPrice": "1500"
}
],
"FiveStar Automotives": [
{
"SparePartID": "51",
"Name": "Brakes",
"Price": "234",
"VendorID": "70",
"CompanyName": "FiveStar Automotives",
"Qty": 1,
"TotalPrice": "234"
},
{
"SparePartID": "53",
"Name": "Clutch",
"Price": "999",
"VendorID": "70",
"CompanyName": "FiveStar Automotives",
"Qty": 1,
"TotalPrice": "999"
},
{
"SparePartID": "55",
"Name": "LED",
"Price": "288",
"VendorID": "70",
"CompanyName": "FiveStar Automotives",
"Qty": 1,
"TotalPrice": "288"
}
]
}
}
我可以这样做通过 localStroage 中的推送方法,或者是否有任何其他方式以这种格式将数据保存在 localStorage 中。我想要这种格式,因为我需要单独处理这些产品的订单。
这是我在 REACT 中的 ADdToCart 方法:
AddToC(part){
console.log("PartID to be added in cart: ", part); //this part shows details of a product in format I mentioned on very top.
const alreadyInCart = JSON.stringify(localStorage.getItem('cartObj'));
alreadyInCart.push(part);
}
编辑:
{this.state.spareParts.map((part, index) =>
<div>
<h4 > {part.Name} </h4>
<h5> Rs. {part.Price} </h5>
<h5> {part.CompanyName} </h5>
<div>
<button onClick={() => this.AddToCart(index, part.SparePartID)}
Add to Cart
</button>
</div>
)}
【问题讨论】:
-
你在哪里存储
records,在状态组件上? -
const unsub = store.subscribe(() => localStorage.setItem("languages", JSON.stringify(store.getState().languages)) );一个简单的例子,如何使用redux进行存储,可能你保存的对象不正确。尝试保存records。 -
@EdisonJunior 我不想使用 redux。有没有其他办法?
-
这是一个简单的前任,你可以使用你想要的,你的
records存储在哪里,你可以分享你的代码吗? -
@EdisonJunior 我在任何地方都没有“记录”。我只是假设当用户在购物车中添加多个项目时记录 JSON 对象,那么数据应该是这样的。我首先想将所有项目存储在 localStorage 上,然后将它们存储在状态组件中
标签: arrays json reactjs local-storage