简体   繁体   中英

How do you set the state of an object passed as a parameter in a function?

I have a function in my React application where I pass in an array of objects. My goal is to loop through this array and update the state of objects that match a condition.

state = {
    productA: {
      total: "",
      transactionFee: 0,
    },
    productB: {
      total: "",
      transactionFee: 0,
    },
}

handleTotalUpdate = (e) => {
    var transactionFee = 0;
    var subTotal = 0;
    e.map((object) => {      
      if (!Number.isNaN(parseInt(object.total))) {
        transactionFee = parseInt(object.total) * 0.02 + 0.1;
        subTotal = parseInt(object.total);        
        this.setState({
          object: {
            total: subTotal,
            transactionFee: transactionFee,
          },
        });
      }
    });
  };

The function gets called like so:

this.handleTotalUpdate([
          this.state.productA,
          this.state.productB,              
        ]),

No problems accessing the properties of the object but when trying to set the state I cannot use the term object as a key. If someone could point me in the right direction of what I'm trying to do and perhaps provide some recommended reading I would appreciate it

  const accumulatedData = e.reduce((acc, object) => {
    if (!Number.isNaN(parseInt(object.total))) {
      transactionFee = parseInt(object.total) * 0.02 + 0.1;
      subTotal = parseInt(object.total);        
      return {
        ...acc,
        object: {
          total: subTotal,
          transactionFee: transactionFee,
        },
      };
    }
  }, {});
  this.setState(accumulatedData);

I don't changed your variable. I think you use reduce than map to solve this.

It help your DOM rerender issues and Data mutations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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