我创建了一个包装器组件,可以使用另一个组件进行配置,以共享一些功能。基本上,包装器组件创建一个新的DomNode并从其道具中呈现子组件,如下所示:
//wrapper
componentDidMount () {
this.node = document.body.appendChild(document.createElement('div'));
}
componentDidUpdate () {
if (this.state.editing) {
ReactDOM.render(this.props.component, this.node);
} else {
ReactDOM.unmountComponentAtNode(this.node)
}
}
//component from within the props of the wrapper above
componentWillUnmount () { /* runs */ }
render () {
return (
<div>
<AnotherThing />
</div>
);
}
componentWillUnmount()
实例的<{strong> <AnotherThing />
永远不会触发。这是默认值,还是我错了?我希望为子树中的所有组件触发componentWillUnmount()
。
更新
这一切都正常运作。我的手表过程停止了工作,这就是我无法看到卸载的原因。
答案 0 :(得分:2)
你现在可以比现在更轻松地实现你想要的目标。
您的渲染功能可能如下所示:
render () {
return (
<div>
{ this.state.editing ? this.props.component : null }
</div>
)
}
render
将在您的州或道具发生变化时运行,因此您不需要单独的生命周期方法来实现您想要实现的目标。 React将负责安装和卸载this.props.component
。