Javascript react-force componentDidUpdate()当道具值相同时
在我的组件中,我试图将收到的道具与当前状态同步,以便从外部看到它(我知道这是一种反模式,但我还没有找到解决方案。我非常愿意听取建议!) 不管怎样,这就是我得到的:Javascript react-force componentDidUpdate()当道具值相同时,javascript,reactjs,react-redux,Javascript,Reactjs,React Redux,在我的组件中,我试图将收到的道具与当前状态同步,以便从外部看到它(我知道这是一种反模式,但我还没有找到解决方案。我非常愿意听取建议!) 不管怎样,这就是我得到的: export class PopupContainer extends React.Component { state = { show: false, }; shouldComponentUpdate(nextProps, nextState) { if (this.props.show === nex
export class PopupContainer extends React.Component {
state = {
show: false,
};
shouldComponentUpdate(nextProps, nextState) {
if (this.props.show === nextProps.show) return true;
return true;
}
componentDidUpdate(prevProps, prevState, snapshot) {
// if popup shown, fade it out in 500ms
if (this.props.show !== prevProps.show)
this.setState({ show: this.props.show });
if (this.state.show) {
setTimeout(() => this.setState({ show: false }), 2000);
}
}
render() {
return <Popup {...{ ...this.props, show: this.state.show }} />;
}
}
导出类PopupContainer扩展React.Component{
状态={
秀:假,,
};
shouldComponentUpdate(下一步,下一步状态){
如果(this.props.show==nextrops.show)返回true;
返回true;
}
componentDidUpdate(prevProps、prevState、快照){
//如果显示弹出窗口,则在500毫秒内淡出
if(this.props.show!==prevProps.show)
this.setState({show:this.props.show});
if(this.state.show){
setTimeout(()=>this.setState({show:false}),2000);
}
}
render(){
返回;
}
}
在我的外部组件中,我正在渲染容器:
<PopupContainer
show={this.state.popup.show}
message={this.state.popup.message}
level={this.state.popup.level}
/>
现在,当我最初将this.state.show
设置为true
时,它起作用了,但是每个连续的赋值都是true
,中间没有任何false
赋值,它不起作用。如何强制componentdiddupdate()
在道具值相同的情况下开火shouldComponentUpdate()
似乎无法解决问题
谢谢大家!
编辑:我注意到
render()
方法只在父元素中调用。似乎孩子的属性没有变化,react甚至不需要麻烦重新命名孩子,这在某种程度上是有道理的。但我怎么能强迫他们重播呢?这是一种黑客行为,但对我来说很有效
在儿童班中
将属性添加到构造函数中的状态-让我们调用它myChildTrigger
,并将其设置为空字符串:
this.state = {
...
myChildTrigger: ''
}
然后将其添加到componentdiddupdate
:
componentDidUpdate(prevProps) {
if(this.state.myChildTrigger !== this.props.myParentTrigger) {
// Do what you want here
this.setState({myChildTrigger: this.props.myParentTrigger});
}
}
在父类中
将myParentTrigger
添加到构造函数中的状态:
this.state = {
...
myParentTrigger: ''
}
在渲染方法中,将其添加为道具,如下所示:
<ChildClass ... myParentTrigger={this.state.myParentTrigger} />
当您需要强制组件重新启动时,可以执行
this.forceUpdate()
,@semuzaboi问题是它实际上正在重新启动。只需组件diddupdate()
方法未调用。shouldComponentUpdate
中的条件在返回true
anyway@barbsan我知道它只是用来证明它并没有解决问题。@Biko Kießling如果可行,试试这个:在shouldComponentUpdate中,而不是this.props.show
tothis.state.show
和nextrops.show到nextState.show
this.setState({ myParentTrigger: this.state.myParentTrigger + 'a' });