First of all, a life cycle map can help us understand better.
Let's take a concrete example to see how react's life cycle is executed.
<script type="text/babel"> /* Requirements: Custom Components 1. Let the specified text be animated for display/hiding 2. Switching time is 2S 3. Click the button to remove the component interface from the interface */ class Fade extends React.Component { constructor (props) { super(props) console.log('constructor(): Creating Component Objects') this.state = { opacity: 1 } this.removeComponent = this.removeComponent.bind(this) } componentWillMount () { console.log('componentWillMount(): Initialization will be mounted') } componentDidMount () {// Start timer / binding listener / send ajax requests in this method console.log('componentDidMount(): Initialization has been mounted') // Save to the current component object this.intervalId = setInterval(function () { console.log('--------') // Get the current opacity let {opacity} = this.state // Update opacity opacity -= 0.1 if(opacity<=0) { opacity = 1 } // Update state this.setState({opacity}) }.bind(this), 200) } componentWillUpdate () { console.log('componentWillUpdate(): Will be updated') } componentDidUpdate () { console.log('componentDidUpdate(): Has been updated') } componentWillUnmount () {// Clear timer/deactivate monitor console.log('componentWillUnmount(): Will be removed') clearInterval(this.intervalId) } removeComponent () { ReactDOM.unmountComponentAtNode(document.getElementById('example')) } render() { console.log('render() Rendering Components') return ( <div> <h2 style={{opacity:this.state.opacity}}>{this.props.content}</h2> <button onClick={this.removeComponent}>Not alive.</button> </div> ) } } ReactDOM.render(<Fade content="react be unable to learn how to do sth., What should I do??"/>, document.getElementById('example')) </script>
The results are as follows:
The order of print life cycle is as follows:
Note: This ES6 class component (complex component) approach, in fact, all life cycles are defined in the React.Component class. When we write components, which life cycle functions should be used, which is equivalent to rewriting the React.Component class method, even if we do not write, it itself has the default!!!
The article is only a record of my learning process, for reference only. If you have any questions, please point out!