在我的组件中,我试图将接收到的道具与当前状态进行同步,以使其从外部可见(我知道这是一种反模式,但是我还没有找到其他解决方案。我非常开放提出建议!)。>
无论如何,这就是我所拥有的:
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 show={this.state.popup.show} message={this.state.popup.message} level={this.state.popup.level} />
现在,当我最初将
this.state.show
设置为true
时,它可以工作,但是每个连续的分配(也就是true
,中间没有任何false
分配)不起作用。即使道具的值相同,我怎么也要强制componentdidUpdate()
开火?shouldComponentUpdate()
似乎无法解决问题。谢谢!
编辑:我注意到render()
方法仅在父元素中调用。看起来好像孩子的属性没有变化,React甚至不费心重新渲染孩子,这在某种程度上是有道理的。但是我怎么能强迫他们重新渲染?
在我的组件中,我试图将收到的道具与当前状态进行同步,以使其从外部可见(我知道这是一种反模式,但是我还没有找到解决此问题的另一种方法...
这是一种技巧,但对我有用。
在子班级