反应状态更新落后 [英] React state update step behind

查看:95
本文介绍了反应状态更新落后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此颜色选择器有效,但落后一步.我一直在使用React 15.4.2. 在更高版本中要解决的问题吗? 如果是我的错,请如何掌握待处理状态"? 笔 http://codepen.io/462960/pen/qrBLje 代码:

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

推荐答案

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

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

第一次调用它时,this.state.today_color仍然是先前的值.

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

您应该执行以下操作:

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

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

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

这是一个有效的示例.

这篇关于反应状态更新落后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆