【发布时间】:2019-07-02 14:03:53
【问题描述】:
我正在使用 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);
`
【问题讨论】:
标签: javascript reactjs local-storage