如何在反应中从地图功能导出数据?

时间:2018-10-29 12:20:37

标签: javascript reactjs ecmascript-6

我是新来的反应者,我正试图用它编写购物车,我需要使用用户从商店中选择的商品数据将其发布到服务器,这是到目前为止的代码:

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,但是我不知道如何从map函数范围导出数据,我也可以' t setState在render方法中(因为这会导致无限循环)。 我该如何设置我的数据?

预先感谢您:-)

2 个答案:

答案 0 :(得分:0)

在您的postOrder()中,您需要像下面的代码示例一样迭代购物车项目。而且,您无需保持数据状态。

postOrder() {
 const itemsSelected = this.props.cart.map((item) => {
    return {
       'id': item.Id,
       'quantity':item.quantity 
    };
 }
 console.log(itemsSelected);
 // now, you can post your selected cart items to server here...
 alert('hello')
}

答案 1 :(得分:0)

getCartData() {
    const cartData = this.state.cart.map(function (cartItem) {
      return {
        'id': cartItem.id,
        'name': cartItem.name
      };
    })
    console.log('cartData',cartData)
    this.setState({ cart: cartData })
  }