English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this chapter, we will discuss component lifecycle methods.
componentWillMount
Executed on both the server and client sides before rendering.
componentDidMount
Executed only after the first rendering is completed on the client side. This is the place where AJAX requests and DOM or state updates should be performed. This method is also used for other JavaScript frameworks and any functions that need to be executed with a delay (e.g.setTimeout
or integratedsetInterval
. We are using it to update the state so that we can trigger other lifecycle methods.
componentWillReceiveProps
Called immediately after prop updates, then call another renderer. We are fromsetNewNumber
Triggered when updating the state.
shouldComponentUpdate
It should returntrue
orfalse
value. This will determine whether the component will be updated.true
Set to default by default. If you are sure that the component does not need to be updated afterstate
orprops
Rendered after the update, you can returnfalse
value.
componentWillUpdate
Called before rendering.
componentDidUpdate
Called immediately after rendering.
componentWillUnmount
Called after the component is unloaded from the DOM. We are in the process of unloading the componentmain.js
.
In the following example, we willstate
Set the initial value in the constructor. ThesetNewnumber
Used for updatesstate
All lifecycle methods are inside the Content component.
import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { data: 0 } this.setNewNumber = this.setNewNumber.bind(this) }; setNewNumber() { this.setState({data: this.state.data + 1) } render() { return ( <div> <button onClick = {this.setNewNumber}>INCREMENT</button> <Content myNumber = {this.state.data}></Content> </div> ); } } class Content extends React.Component { componentWillMount() { console.log('Component WILL MOUNT!') } componentDidMount() { console.log('Component DID MOUNT!') } componentWillReceiveProps(newProps) { console.log('Component WILL RECEIVE PROPS!') } shouldComponentUpdate(newProps, newState) { return true; } componentWillUpdate(nextProps, nextState) { console.log('Component WILL UPDATE!'); } componentDidUpdate(prevProps, prevState) { console.log('Component DID UPDATE!') } componentWillUnmount() { console.log('Component WILL UNMOUNT!') } render() { return ( <div> <h3>{this.props.myNumber}</h3> </div> ); } } export default App;
import React from 'react'; import ReactDOM from 'react-dom; import App from '.'/App.jsx'; ReactDOM.render(<App/, document.getElementById('app')); setTimeout(() => { ReactDOM.unmountComponentAtNode(document.getElementById('app'));}, 10000);
After the initial rendering, we will get the following screen.