简体   繁体   中英

Cannot get correct state of checkbox

Something weird is happening. Im using foundation switch as my checkbox.

When I look at my state on the react browser tool, my check state is true. When I console log the state in the handler, it's false. Where is the bug?

es6:

constructor(props){
  super(props);
  this.state = {
    checked: false
  },
  this._handleChange = this._handleChange.bind(this)
}

_handleChange(){
  this.setState({ checked: !this.state.checked });
  console.log(this.state.checked); // becomes the opposite the state!
}

render:

<div className="switch">
  <input className="switch-input" id="exampleSwitch" type="checkbox" onChange={this._handleChange} checked={this.state.checked} name="exampleSwitch">
  <label className="switch-paddle" htmlFor="exampleSwitch">
    <span className="show-for-sr">Download Kittens</span>
  </label>
</div>

When clicked, my react console shows it as true but in console, it's false . The console.log() shows the opposite of the state. If the state is false then the log shows true . Any reason?

Edit for another method:

_onSubmit(){
 let checked = this.state.checked;
 $.ajax({
  ...
  data: {"checked": checked },
  ...
 });
}

From React documentation :

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

So console.log() may work in unexpected manner here. To get proper result you probably would like to pass 2nd argument to your setState() :

The second (optional) parameter is a callback function that will be executed once setState is completed and the component is re-rendered.

_handleChange(){
  this.setState({ checked: !this.state.checked }, () => {
    console.log(this.state.checked); // output will be as expected
  });  
}

setState() is not a synchronous action and therefore the API gives you the ability to give it a callback to do something when the setState() completes. Example below with code that is not tested. Documentation : Facebook setState() documentation.

 var Component = React.createClass({ getInitialState: function() { return ({ initialState: true }); }, changeState: function() { this.setState({ initialState: false }, function() { console.log(this.state.initialState); // this is the callback }); }, render: function() { return ( <button type="button" onClick = {this.changeState}> Test component </button> ); } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 

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