【问题标题】:React state update step behind反应状态更新落后一步
【发布时间】:2017-07-15 00:17:54
【问题描述】:

此颜色选择器有效,但落后了一步。我一直在使用 React 15.4.2。 在以后的版本中是否有问题要修复? 如果是我的错,请问如何掌握“待定状态条件”? 笔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>)
  }
}) 

【问题讨论】:

    标签: reactjs state


    【解决方案1】:

    您遇到的问题是,一旦您调用 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));
    

    这确保 setProperty 在 setState 完成并且在您的状态中具有正确值之后被调用。

    编辑:这是一个有效的example

    【讨论】:

    • 我也是,@paqash,这就是为什么我对你的要求有点惊讶,考虑到规则,我以这种方式表达了我的感激之情。这两个向上的箭头之一来自我。
    • 是的,但是点赞不等于接受答案...stackoverflow.com/help/accepted-answer
    • 我的错,@paqash。你的回答很充实。
    猜你喜欢
    • 2021-05-01
    • 1970-01-01
    • 2021-04-09
    • 2022-06-28
    • 2020-03-26
    • 1970-01-01
    • 2021-06-04
    • 2020-08-02
    • 2019-04-05
    相关资源
    最近更新 更多