来自官方教程:
componentWillUnmount()
is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any DOM elements that were created incomponentDidMount
我理解“使计时器无效”。 fetch
可以用 AbortController
中止。但我不明白“清理在 componentDidMount
中创建的任何 DOM 元素”,我可以查看这种情况的示例吗?
最佳答案
如果网络请求发送库支持中止正在进行的网络请求调用,你当然可以在componentWillUnmount
方法中调用它。
然而,关于DOM
元素的清理是值得关注的。我将根据我目前的经验举几个例子。
第一个是-
import React, { Component } from 'react';
export default class SideMenu extends Component {
constructor(props) {
super(props);
this.state = {
};
this.openMenu = this.openMenu.bind(this);
this.closeMenu = this.closeMenu.bind(this);
}
componentDidMount() {
document.addEventListener("click", this.closeMenu);
}
componentWillUnmount() {
document.removeEventListener("click", this.closeMenu);
}
openMenu() {
}
closeMenu() {
}
render() {
return (
<div>
<a
href = "javascript:void(0)"
className = "closebtn"
onClick = {this.closeMenu}
>
×
</a>
<div>
Some other structure
</div>
</div>
);
}
}
这里我删除了我在组件挂载时添加的点击事件监听器。
第二个是-
import React from 'react';
import { Component } from 'react';
import ReactDom from 'react-dom';
import d3Chart from './d3charts';
export default class Chart extends Component {
static propTypes = {
data: React.PropTypes.array,
domain: React.PropTypes.object
};
constructor(props){
super(props);
}
componentDidMount(){
let el = ReactDom.findDOMNode(this);
d3Chart.create(el, {
width: '100%',
height: '300px'
}, this.getChartState());
}
componentDidUpdate() {
let el = ReactDom.findDOMNode(this);
d3Chart.update(el, this.getChartState());
}
getChartState() {
return {
data: this.props.data,
domain: this.props.domain
}
}
componentWillUnmount() {
let el = ReactDom.findDOMNode(this);
d3Chart.destroy(el);
}
render() {
return (
<div className="Chart">
</div>
);
}
}
在这里,我尝试将 d3.js
与 react 集成到 componentWillUnmount
中;我正在从 DOM 中删除图表元素。
除此之外,我还使用 componentWillUnmount
在打开后清理引导模式。
我确信还有大量其他用例,但这些是我使用过 componentWillUnMount
的用例。希望对您有所帮助。
关于javascript - 如何在 ReactJs 中正确使用 componentWillUnmount(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40760308/