Jef*_*ear 11 reactjs react-dom
我SettingsTab在一个名为的包装器中呈现一个React组件TeamView.它的API看起来像
class TeamView {
constructor() {
this.el = document.createElement('div');
}
render() {
ReactDOM.render(<SettingsTab/>, this.el);
return this;
}
remove() {
this.el.remove();
}
}
Run Code Online (Sandbox Code Playgroud)
用过类似的东西
// to present the team view
const teamView = new TeamView();
document.body.appendChild(teamView.render().el);
// to remove the team view
teamView.remove();
Run Code Online (Sandbox Code Playgroud)
我想知道的是,在打电话之前应该TeamView#remove打电话ReactDOM. unmountComponentAtNode(this.el)this.el.remove()吗?
我可以在网络上找到的示例使得看起来unmountComponentAtNode只需要在容器将保留在DOM中时才需要调用它; 并且新的门户示例只是删除容器,而不调用unmountComponentAtNode.
但是,我不确定这是否特别,因为它正在使用门户网站,而且这篇帖子让人觉得打电话总是好的做法unmountComponentAtNode.
Dan*_*mov 15
是的,重要的是要打电话,unmountComponentAtNode()因为如果你不这样做,树下面的任何组件都不会知道它们已被卸载.
用户定义的组件通常会执行某些操作,componentDidMount从而在全局环境中创建对树的引用.例如,您可以添加一个window事件处理程序(不受React管理),一个Redux商店订阅,一个setInterval调用等.只要这些绑定被删除,所有这些都很好并且正常componentWillUnmount.
但是,如果您只是从DOM中删除根但从不调用unmountComponentAtNode,则React将不知道该树中的组件是否需要卸载.由于它们componentWillUnmount永远不会触发,所以这些订阅会保留,并防止整棵树被垃圾收集.
因此,出于所有实际目的,如果要删除该容器节点,则应始终卸载root.否则你很可能会得到一个内存泄漏 - 如果不是现在,那么稍后当你的一些组件(可能在树的深处,甚至可能来自第三方库)中添加订阅时componentDidMount.
| 归档时间: |
|
| 查看次数: |
4981 次 |
| 最近记录: |