来自官方教程:
在卸载和销毁组件之前立即调用
componentWillUnmount()
.在此方法中执行任何必要的清理,例如使计时器无效、取消网络请求或清理componentDidMount
中创建的任何DOM元素
我理解"使计时器失效".fetch
可以用AbortController
中止.但我不明白"清理componentDidMount
中创建的任何DOM元素",我能看看这种情况的例子吗?
来自官方教程:
在卸载和销毁组件之前立即调用
componentWillUnmount()
.在此方法中执行任何必要的清理,例如使计时器无效、取消网络请求或清理componentDidMount
中创建的任何DOM元素
我理解"使计时器失效".fetch
可以用AbortController
中止.但我不明白"清理componentDidMount
中创建的任何DOM元素",我能看看这种情况的例子吗?
如果网络请求发送库支持中止正在进行的网络请求调用,那么您完全可以在componentWillUnmount
方法中调用它.
然而,关于DOM
个元素的清理是令人担忧的.根据我目前的经验,我将举几个例子.
First one is -
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>
);
}
}
在这里,我删除了在安装组件时添加的click event listener.
Second one is -
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
个用例.我希望它能帮助你.