React 状态更新落后一步

React state update step behind

这个颜色选择器工作但落后了一步。我一直在使用 React 15.4.2。 在以后的版本中是否会修复这个问题? 万一是我的错,请高手如何"pending state condition"? 笔http://codepen.io/462960/pen/qrBLje 代码:

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>)
  }
}) 

您遇到的问题是,一旦您调用 setState,组件就会重新呈现并且不会再次调用此代码:

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

并且第一次调用时,this.state.today_color还是之前的值

你应该做的是:

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

这可确保在 setState 完成后以及在您的状态中具有正确的值后调用 setProperty。

编辑:这是一个有效的 example