如果網絡請求發送庫支持中止正在進行的網絡請求調用,您可以明確地調用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
與反應。在componentWillUnmount
我正在從dom中刪除圖表元素。
除此之外,我已使用componentWillUnmount
打開後清理引導模式。
我確定有很多其他用例,但這些都是我用過的情況。我希望它能幫助你。