如果你定义了 componentWillUnmount 方法,React 会在你的组件被移除屏幕(卸载)之前调用它。此方法常常用于取消数据获取或移除监听事件。
componentWillUnmount 内部的逻辑应该完全"对应"到 componentDidMount 内部的逻辑,例如,如果你在 componentDidMount 中设置了一个监听事件,那么 componentWillUnmount 中就应该清除掉这个监听事件。如果你的 componentWillUnmount 的清理逻辑中读取了一些 props 或者 state,那么你通常还需要实现一个 componentDidUpdate 来清理使用了旧 props 和 state 的资源(例如监听事件)。
import React from 'react';
import './App.css';
class Bpp extends React.Component {
componentWillUnmount() {
console.log('组件卸载');
}
render() {
return (
<div>
<h1>我是Bpp组件</h1>
</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
bpp_show:true
};
}
componentDidMount() {
console.log('组件挂载完成');
}
//定义事件
click = () => {
this.setState({
bpp_show:false
}) }
// 渲染组件UI,返回React元素
render() {
const { bpp_show } = this.state;
return (
<div>
{bpp_show && <Bpp></Bpp>}
<button onClick={this.click}>
隐藏bpp
</button>
</div>
)
}
}
export default App;