繁体   English   中英

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

[英]How to add a callback function to the .map method

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

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>

             ); 

    }

});

两点:

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

在伪代码中,组件的结构应类似于:

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>
    );
  } 
}

地图是同步的。 为什么需要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>

             ); 

    }

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM