React state update step behind

2019-06-14 04:48发布

问题:

This color picker works but one step behind. I've been using React 15.4.2. Is it an issue to be fixed in later versions? In case it's my fault, please, how to master "pending state condition"? Pen http://codepen.io/462960/pen/qrBLje Code:

let Input =  React.createClass({
  getInitialState(){
        return {
        today_color: "#E5D380"
    };
    },
  colorChange(e){
        this.setState({
            today_color: e.target.value
        })
        document.querySelector('html').style.setProperty('--base', this.state.today_color);
     },
  render(){
    return (<div>
           <input className="today_color" onChange={this.colorChange} type="color" defaultValue={this.state.today_color}/>
           </div>)
  }
}) 

回答1:

The issue you are having is that once you call setState the component rerenders and this code isn't called again:

document.querySelector('html').style.setProperty('--base', this.state.today_color);

And the first time it is called, this.state.today_color is still the previous value.

What you should do is the following:

this.setState({
  today_color: e.target.value
}, () => document.querySelector('html').style.setProperty('--base', this.state.today_color));

This makes sure the setProperty gets called after setState is done and after you have the correct value in your state.

Edit: here's a working example.



标签: reactjs state