Throughout the life of a component, as the props or state of the component changes, its DOM representation changes accordingly. A component is a state machine that always returns consistent output for a given input.
The life cycle of a component can be divided into three states:
- Mounting: The real DOM is inserted
- Updating: Being rerendered
- Unmounting: The real DOM has been removed
The first state (instantiation phase)
- GetDefaultProps: This method is called only once for each component instance and can be used to set the default props value
- GetInitialState: This method is called once and only to initialize the state for each instance
- ComponentWillMount: The last chance to modify the state before the Render method is called. It can be used to set the props parameters to state
- ComponentDidMount:
- When this method is called, the real DOM has already been rendered and can be accessed in this method via this.getDomNode () (reactdom.finddomNode () is recommended).
- Will not be called during server rendering (can be used to get canvas ID /ref, etc.)
- The page has been loaded to listen for the page
Render (= render)
Second state (lifetime)
- ComponentWillReceiveProps (nextProps) :
- Update state in this method to trigger the Render method to rerender the component
- To listen for changes in the props (the value that needs to listen for changes is stored in state for comparison)
if(nextProps .x ! = =this.state.x ){
}
Copy the code
- ShouldComponentUpdate: If you are sure that the component’s props or state changes do not need to be re-rendered, you can prevent the component from re-rendering by returning false in this method. Returning false will not execute render and the following componentWillUpdate. ComponentDidUpdate method
- ComponentWillUpdate:
- ComponentWillUpdate (Object nextState) is called before the component receives new props or is about to re-render
- Don’t update props or state in this area
Third State (Destruction Period)
- ComponentDidUpdate: After the component is re-rendered, componentDidUpdate(Object prevProps, Object prevState) is called. You can access and modify the DOM here
- componentWillUnmount:
- Whenever React uses a component, the component must be uninstalled from the DOM and then destroyed. This method is used to remove all cleanup and destruction for componentWillUnmout. Such as created timers or event listeners
- Components are not unloaded when you refresh the browser; they are unloaded only when you leave the page
- Unload the component when you leave the page, and clear the value in state
componentWillUnmount(){
// Override the setState method of the component to return null
this.setState = (state,callback) = >{
return;
};
}
Copy the code
Reference: segmentfault.com/a/119000000…