首页 > 解决方案 > this.props 在 shouldComponentUpdate 运行之前更新

问题描述

我有我的ClockBlock组件,我提升状态保持在对象“计时器”中:

class ClockBlock extends Component {
  constructor(props){
    super(props);
    this.state = { timer: props.timer }; // timer from Redux store
  }

  render(){
    return(
      <div className="clockBlock">
        <Circle timer={this.state.timer} updateTimer={this.updateTimer.bind(this)} />
        <Clock timer={this.state.timer} updateTimer={this.updateTimer.bind(this)} />
        <ClockTerms updateTimer={this.updateTimer.bind(this)} />
      </div>
    )
  }

这三个嵌套组件都通过updateTimer函数相互影响。(除了 ClockTerms 组件 - 它在一个方向上工作)。功能在这里:

 updateTimer(newDuration){
    const newState = Object.assign( {}, this.state );
    newState.timer.duration = newDuration;
    this.setState( newState );
  }

所以,问题 - 当我使用ClockTerms组件更改计时器时,我也看到组件中的更改Clock(显然是通过道具)。同时Circle在功能组件中,shouldComponentUpdate我试图查看旧道具和新道具之间的区别。这是这个函数:

 shouldComponentUpdate(nextProps, nextState){
    console.log( this.state.timer );
    console.log( nextState.timer );
    console.log( this.props.timer );
    console.log( nextProps.timer );

    return true;
 }

所有的 console.log() 调用都打印相同的数据——新的道具。为什么?我怎样才能得到旧道具?

PS:我简化了上面的代码,从我的角度计算中删除了不相关的内容。可以给出完整的代码,如果它很重要。我在这里也使用 Redux,但在我看来,这里并没有太多参与。非常感谢提前!

更新:在(父)组件中放置相同的shouldComponentUpdate功能时,我也会得到相同的图片;ClockBlock

标签: reactjsreact-redux

解决方案


通过将 this.state 与 nextProps 进行比较并更新状态,我解决了类似的情况。我不认为这是一个很好的解决方案,但没有想出其他任何喷气机。

state = {
    dayOff: this.props.myProperty
}

shouldComponentUpdate(nextProps, nextState) {
    const shouldUpdate = this.state.myProperty !== nextProps.myProperty;
    if (shouldUpdate) this.state.myProperty = nextProps.myProperty
    return shouldUpdate;
}

推荐阅读