如何向.map方法添加回调函数

时间:2016-04-22 09:05:50

标签: javascript reactjs

我希望我的函数计算购物车的总成本,然后将我的组件的状态设置为总计,但我需要先完成计算,然后在计算完成后设置状态。当我运行下面的代码时,状态永远不会被设置。

renderCart: function() {

        var newSubtotal = 0;
        var newTotal = 0;

        this.props.cart.map((product)=>{

            newSubtotal += product.price;
            newTotal += product.price;
            newTotal *= 1.10;

            console.log("New Total ", newTotal);
            console.log("New Subtotal ", newSubtotal);

        }, () => {
            this.setState({
              subtotal: newSubtotal,
              total: newTotal
            });
        });


        return (
                    <div>
                        <ul>
                            <li>Subtotal: ${this.state.subtotal}</li>
                            <li>Discount: {this.state.discount}%</li>
                            <li>Tax: {this.state.tax}%</li>
                            <li>Total: ${this.state.total}</li>
                        </ul>
                      <button className="success button">Pay</button>
                    </div>

             ); 

    }

});

3 个答案:

答案 0 :(得分:1)

两点:

  1. 你应该使用.reduce函数计算总和。
  2. 你不应该在你的render()中使用this.setState,我建议使用ComponentDidMount或InitialState

答案 1 :(得分:1)

在伪代码中,组件的结构应该更像:

MyCartTotalComponent => {
  // no need for state: if your props contain cart, then every time cart changes
  // your component gets new props, calculates total, and renders
  render() {
    // calculate stuff and store in local cart variable
    var cart = {};
    cart.total = this.props.cart.reduce(
      function(prev,curr){
        return prev + curr.price;
      },0);
    // render stuff
    return (
      <div>
         ...
         <li>{cart.Total}</li>
         ...
      </div>
    );
  } 
}

答案 2 :(得分:0)

地图是同步的。为什么需要setState,使用足够的变量。

renderCart: function() {

        var newSubtotal = 0;
        var newTotal = 0;

        this.props.cart.map((product)=>{

            newSubtotal += product.price;
            newTotal += product.price;
            newTotal *= 1.10;

            console.log("New Total ", newTotal);
            console.log("New Subtotal ", newSubtotal);

        });


        return (
                    <div>
                        <ul>
                            <li>Subtotal: ${newSubtotal}</li>
                            <li>Discount: {this.state.discount}%</li>
                            <li>Tax: {this.state.tax}%</li>
                            <li>Total: ${newTotal}</li>
                        </ul>
                      <button className="success button">Pay</button>
                    </div>

             ); 

    }

});