我是新手,我正在尝试用它编写购物车,我需要使用用户从商店中选择的商品数据将其发布到服务器这是我的代码到目前为止:
import React,{Component} from 'react'
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';
class Food extends Component{
constructor(props){
super(props);
this.state = {
items:[],
cart:[]
};
this.addToCart=this.addToCart.bind(this);
}
componentWillReceiveProps(){
if (this.props.product.length > 0){
var info = this.props.product;
this.setState({items: info});
}
}
addToCart(item){
var found = false;
var updatedCart = this.state.cart.map((cartItem)=>{
if(cartItem.Name === item.Name){
found = true;
cartItem.quantity++;
return cartItem;
} else{
return cartItem;
}
});
if (!found) {
updatedCart.push({Id: item.ProductID, Name: item.Name, Price: item.Price, quantity: 1})
}
this.setState({
cart: updatedCart
});
}
render(){
var products = this.state.items.map((item) => {
return <Product details={item} addToCart={this.addToCart} key={item.ProductID} />
})
return (
<div>
<nav>
<div><h3>{this.props.cat}</h3></div>
<Cart cart={this.state.cart}/>
</nav>
<div className="Products">
{products}
</div>
</div>
);
}
}
class Cart extends Component{
constructor(props){
super(props);
this.state = {
open : false,
total:0,
quantity: 0
};
this.openCart = this.openCart.bind(this);
this.postOrder = this.postOrder.bind(this);
}
openCart(){
this.setState({open : !this.state.open});
}
postOrder(){
alert('hello')
}
render(){
return(
<div>
<div className={"Cart " + (this.state.open ? "Cart-Open" : "")} onClick={this.openCart}>
<p className="Title">Cart</p>
<div>
{this.props.cart.length > 0 ? this.props.cart.map((item) => {
var itemSelected = [{'id': item.Id, 'quantity':item.quantity}]
console.log("result",itemSelected);
console.log("total",item.quantity*item.Price);
return <p key={item.Id}>{item.Name}{item.quantity > 1 ? <span> {item.quantity}</span> : ''}</p> }) : <p>Empty</p>}
</div>
total : {this.state.total}
</div>
<Button variant="contained" color="primary" onClick={this.postOrder}>
خرید
</Button>
</div>
)
}
}
class Product extends Component{
constructor(props){
super(props);
this.state = {
};
this.addToCart = this.addToCart.bind(this);
}
addToCart(){
this.props.addToCart (this.props.details);
}
render(){
let item = this.props.details;
return(
<div className="Product" onClick={this.addToCart}>
<Grid container spacing={24}>
<Grid item xs={6} key={item.ProductID}>
<Paper className="food-item">
<p>{item.Name}</p>
<p>{item.Excerpt}</p>
<p>{item.Price}</p>
</Paper>
</Grid>
</Grid>
</div>
)
}
}
export default Food;
正如您在购物车组件中看到的那样,我获取用户选择的数据并将其存储到“itemSelected”变量现在我想要 setState 但我不知道如何从地图函数范围导出数据,我也无法 setState 它在渲染方法内部(因为这会导致无限循环)。我如何设置我的数据?
先感谢您 :-)