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

How to add a callback function to the .map method

本文关键字:map 方法 添加 函数 回调      更新时间:2023-09-26

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

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

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

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

两点:

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

映射是同步的。为什么需要 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>
             ); 
    }
});
相关文章: