我正在使用React在一个电子商务项目中,通过单击所需的产品,将其通过localStorage.setItem保存,然后始终通过购物车组件中的localStorage.getItem显示。一切正常,直到我单击另一个产品。碰巧的是,它取代了之前选择的产品而不是将其添加到购物车中。 如何添加多个产品?
//component "HomeProduct.js" in which I show the products
export const data = {
"products":[
{
"id": 8,
"img": "img1",
"img2": "img2",
"img3": "img3",
"name": "Product Name1",
"price": 265.90,
"description": "Lorem ipsum dolor sit amet, consectetur."
},
{
"id": 9,
"img": "img1",
"img2": "img2",
"img3": "img3",
"name": "Product Name2",
"price": 695.99,
"description": "Lorem ipsum dolor sit amet, consectetur.",
}
]
}
class HomeProduct extends React.Component{
render(){
return(
<>
{data.products.map((products, key) =>
<Link to={{
pathname: `/Product/${products.id}`,
state: products
}}>
<Button key={key}>
<Image src={products.img}/>
<span>{products.name}</span>
<span>${products.price}</span>
</Button>
</Link>
)}
</>
)
}
}export default HomeProduct;
//"ProductItem.js", component of "Product.js" in in which
//the product details are shown and the button to put it in the cart
class ProductItem extends React.Component{
render(){
const {location} = this.props
function addProductToCart() {
localStorage.setItem('id', location.state.id);
localStorage.setItem('name', location.state.name);
localStorage.setItem('price', location.state.price);
localStorage.setItem('img', location.state.img);
localStorage.setItem('description', location.state.description);
}
return(
<>
<Row id={location.state.id}>
<Col>
<div>
<img src={location.state.img}/>
</div>
<div>
<img src={location.state.img2}/>
</div>
<div>
<img src={location.state.img3}/>
</div>
</Col>
<Col>
<h1>{location.state.name}</h1>
<h1>${location.state.price}</h1>
</Col>
<Col>
<p>{location.state.description}</p>
</Col>
<Button
onClick={addProductToCart}
>Add to Cart</Button>
</Row>
</>
)
}
}export default withRouter(ProductItem);
//"CartProduct.js", component of the cart
export const showProduct = () => {
localStorage.getItem('id');
localStorage.getItem('name');
localStorage.getItem('price');
localStorage.getItem('img');
localStorage.getItem('description');
}
export const CartProduct = () =>(
(localStorage.getItem('id') !== null) ? (
<>
<Row id={localStorage.getItem('id')}>
<Col>
<img src={localStorage.getItem('img')}/>
</Col>
<Col>
<h4>{localStorage.getItem('name')}</h4>
<span>{localStorage.getItem('description')}</span>
<h4>${localStorage.getItem('price')}</h4>
</Col>
<Col>
<Form>
<Form.Row >
<Form.Group>
<Form.Control type="number" defaultValue="1" min="1" count="1"/>
</Form.Group>
</Form.Row>
</Form>
</Col>
</Row>
</>
):(
<span/>
)
)
export default withRouter(CartProduct);
`
答案 0 :(得分:0)
这里发生的事情是您要覆盖存储产品的密钥。如果您执行localStorage.setItem('id', something)
,则在localStorage.setItem('id', otherThing)
之后。当您执行localStorage.getItem('id')
时,会得到otherThing
,因为在将项目设置为something
时,它会被覆盖。
在localStorage
中,您只能拥有唯一的键。同一键不能有多个值。
要保存多个产品,应该做的就是将产品保存为阵列。
function addProductToCart() {
let productsString = localStorage.getItem('products')
let products = []
if(productsString){
products = JSON.parse(productsString)
}
products.concat([location.state])
localStorage.setItem('products', JSON.stringify(products)) // set products as an array
}
获得产品时,您将获得所有产品的完整阵列。
const showProduct = () => {
localStorage.getItem('products'); // gets an array of the products
}
如果您想获得最后的产品,应该这样做
const getLastProduct = () => {
let productString = localStorage.getItem('products')
let products = JSON.parse(productString)
return products[products.length - 1]
}
您应该注意,应该使用JSON.stringify
保存该数组,并使用JSON.parse
来获取它。
答案 1 :(得分:0)
我能够添加一个以上的产品,我必须修改的代码部分如下:
//ProductItem.js
const {location} = this.props
function addProductToCart() {
const oldproduct = localStorage.getItem('products') ? localStorage.getItem('products') : "[]";
const arrayproduct = JSON.parse(oldproduct);
let productsString = data.products;
let products = location.state
arrayproduct.push(products);
if(productsString){
products = JSON.parse(productsString)
}
localStorage.setItem('products', JSON.stringify(arrayproduct));
}
我还必须涉及包含CartProduct的主要组件:
//Shopping.js
export default class Shopping extends Component{
componentDidMount(){
const products = JSON.parse(localStorage.getItem('products'));
this.setState({products});
}
render(){
const products = JSON.parse(localStorage.getItem('products'));
return(
{products.map((product, key) =>
<CartProduct key={key} data={product}/>
)}
)
}
//CartProduct.js
class CartProduct extends React.Component{
render(){
return(
(localStorage.getItem('products') !== null) ? (
<>
<Row>
<Col>
<img src={this.props.data.img}/>
</Col>
<Col>
<h4>{this.props.data.name}</h4>
<span>{this.props.data.description}</span>
<h4>${this.props.data.price}</h4>
</Col>
</>
):(
<span/>
)
)
}}export default withRouter(CartProduct);
答案 2 :(得分:0)
const addToCart = (data) => {
var dataCart = JSON.parse(localStorage.getItem('cart'))
var product = data
product['amount'] = 1
if (dataCart.length === 0 || !dataCart.find((p) => p.name === product.name)) {
dataCart.push(product)
localStorage.setItem('cart', JSON.stringify(dataCart))
} else if (dataCart.find((p) => p.name === product.name)) {
product['amount'] += dataCart.find((p) => p.name === product.name).amount
dataCart.splice(
dataCart.findIndex((p) => p.name === product.name),
1,
product
)
localStorage.setItem('cart', JSON.stringify(dataCart))
}
}