React componentWillUnmount() Method

React 组件生命周期React Component Lifecycle

The componentWillUnmount() method format is as follows:

componentWillUnmount()

The componentWillUnmount() method is called directly before the component is unmounted and destroyed.

You should not call setState() in the componentWillUnmount() method, because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.

In the following example:componentWillUnmount()The method will be called when the component is about to be removed from the DOM:

Example

class Container extends React.Component { constructor(props) { super(props); this.state = {show: true}; } delHeader = () => { this.setState({show: false}); } render() { let myheader; if (this.state.show) { myheader = <Child />; }; return ( <div> {myheader} <button type="button" onClick={this.delHeader}>Delete title component</button> </div> ); } } class Child extends React.Component { componentWillUnmount() { alert("The title component is about to be unmounted."); } render() { return ( <h1>Hello Example!</h1> ); } }

Try it »

React 组件生命周期React Component Lifecycle

Other Extensions