reactjs - 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
解决方案
通过将 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;
}
推荐阅读
- java - java删除导致.0变为.99的尾随十进制数字
- python - 使用 Flask 单击链接后转到图像
- python - 将 PCA 组件与数据集中的其余特征连接起来
- timeout - 无法修复后缀 421 超时超时错误
- amazon-web-services - EC2 窗口实例 - 粘贴文件
- php - PHP mysqli 和 SSL
- javascript - 不和谐.js | 您只能批量删除 14 天以内的邮件
- html - 为什么rowspan“3”会删除一整行并将其设置为“2”
- asp.net-core - AspNet Core 3.0-3.1 无法捕获未处理的异常(应用程序崩溃)
- discord - Discord.js 将 DM 消息转发到特定频道