简体   繁体   中英

React - Passing value to setState callback

I'm trying to pass a value determined outside my prevState callback into the function. Here is what I have:

uncheckAllUnsentHandler = (e) => {
    const newCheckMarkValue = e.target.checked;
    this.setState((prevState, props, newCheckMarkValue) => {
      const newUnsentMail = prevState.unsentMail.map(policy => {
        mail.willSend = newCheckMarkValue;
        return mail;
      });
      return {
        unsentMail: newUnsentMail
      }
    });
  }

newCheckMarkValue is undefined inside the map function and I'm not sure why.

Long description: I have a table where clients select whether they want to send mail or not. By default all mail items are checked in the table. In the header they have the ability to uncheck/check all. I'm trying to adjust the state of the mail items in the table to be unchecked (willSend is the property for that on Mail) when the header checkbox is clicked to uncheck. All of this works if I hardcode the willSend to true or false in code (ex: mail.willSend = true;) in the code below, but I can't seem to get the value of the of the checkbox in the header in.

setState

The updater function takes only two arguments, state and props . state is a reference to the component state at the time the change is being applied.

(state, props) => stateChange

You can simply access the version of newCheckMarkValue enclosed in the outer scope of uncheckAllUnsentHandler .

uncheckAllUnsentHandler = (e) => {
  const newCheckMarkValue = e.target.checked;
  this.setState((prevState, props) => {
    const newUnsentMail = prevState.unsentMail.map(policy => {
      mail.willSend = newCheckMarkValue;
      return mail;
    });
    return {
      unsentMail: newUnsentMail
    }
  });
}

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