React componentWillUnmount() 方法
componentWillUnmount() 方法格式如下:
componentWillUnmount()
componentWillUnmount() 方法在组件卸载及销毁之前直接调用。
componentWillUnmount() 方法中不应调用 setState(),因为该组件将永远不会重新渲染。组件实例卸载后,将永远不会再挂载它。
以下实例中 componentWillUnmount() 方法会在组件即将从 DOM 中移除时调用:
实例
classContainerextendsReact.Component{constructor(props){super(props);
this.state = {show: true};
}delHeader = () => {this.setState({show: false});
}render(){letmyheader;
if(this.state.show){myheader = <Child />;
};
return(
<div>
{myheader}
<buttontype="button"onClick={this.delHeader}>删除标题组建</button>
</div>
);
}}classChildextendsReact.Component{componentWillUnmount(){alert("标题组件即将卸载。");
}render(){return(
<h1>HelloRunoob!</h1>
);
}}ReactDOM.render(<Container />, document.getElementById('root'));
尝试一下 »