React state update step behind

自闭症网瘾萝莉.ら 提交于 2019-12-08 10:21:35

问题


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.



来源:https://stackoverflow.com/questions/42434013/react-state-update-step-behind

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!