简体   繁体   中英

How to change state value when checkbox change using ReactJS

Im currently using React for a project where i work and i'm struggling binding state with the form i'm creating. So i have this :

getInitialState: function() {
    return {
        proofDivulgation: false,
        proofDivulgationFedex: false,
        proofDivulgationMail: false,
        noticeRecidivism: false,
        noticeRecidivismFedex: false,
        noticeRecidivismEmail: false,
        fedexAccount: '',
        emergyContact: false

    };

And i want to change those booleans whenever i'll modify a checkbox ( the value of those booleans should be the same as the checked value of a checkbox ). I got this React component too

<Toggle defaultChecked={this.state.proofDivulgation} onChange={this.handleCheckboxChange(this.state.proofDivulgation)} />

and this is the method attached to the onChange event :

handleCheckboxChange: function(booleanToSwitch){
  console.log(booleanToSwitch);
  this.replaceState({booleanToSwitch : true})
},

which give me this error : replaceState(...): Cannot update during an existing state transition (such as withinrender). Render methods should be a pure function of props and state. replaceState(...): Cannot update during an existing state transition (such as withinrender). Render methods should be a pure function of props and state.

Is there any work-around i could do ? I simply need a basic function that'll invert the boolean value of a state passed as a parameters

You are calling that function immediately, not on change.

  1. React runs render ;
  2. It finds an onChange parameter;
  3. If it's a function reference then nothing happens;
  4. If it's a function call then the function is called when the code runs and the result is passed as the callback to onChange ;
  5. When you click on the checkbox that function reference (callback) is called;

What your code does is set the return value of this.handleCheckboxChange(this.state.proofDivulgation) as the callback for onChange .

What you need is this:

handleCheckboxChange: function(booleanToSwitch) {
  return function(event) {
    console.log(booleanToSwitch);
    this.replaceState({booleanToSwitch : true})
  };
},

Also I'm pretty sure you'll need

this.state[booleanToSwitch] = true;

instead.

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