React componentWillUnmount() method


Release date:2024-03-15 Update date:2024-03-15 Editor:admin View counts:37

Label:

React componentWillUnmount() method

componentWillUnmount() format of the method is as follows:

componentWillUnmount()

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

componentWillUnmount() method should not be called setState() because the component will never be re-rendered After the component instanceis uninstalled, it will never be mounted again.

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

Example

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}>
Delete Title Build</button>
</div>);}}classChildextendsReact.Component{componentWillUnmount(){alert
("The title component is about to be uninstalled.");}render(){return(<h1>HelloRunoob!</h1>);}}ReactDOM.render
(<Container/>,document.getElementById('root'));

Powered by TorCMS (https://github.com/bukun/TorCMS).