The React component lifecycle

The constructor argument takes two parameters, props, and context, which are passed from the parent component. If you want to use the constructor argument inside the props function, the context can be used as an example. To use props or context, which can be received directly elsewhere in the component, you need to pass in, and pass in, the super object.

Constructor (props,context) {super(props,context) console.log(this.props,this.context) // Internally use props and context}Copy the code

As long as the component has constructor, you must write super, otherwise the this reference will be wrong

Constructor () {console.log(this);}Copy the code

2. ComponentWillMount The component will be mounted

The component has just undergone constructor, the data component has not yet entered render after initialization, the component has not yet rendered, the DOM has not yet been rendered and is called before the component is mounted, and is called globally only once. If you can setState in this hook, you can see the updated state after render, it will not trigger repeated rendering. This lifecycle can initiate asynchronous requests and setState. (Deprecated after React V16.3, state can be set in constructor) But there is a problem

Are ajax requests recommended in willmount? : The answer is no. Don’t write that

Although in some cases nothing will go wrong, if the data in the Ajax request is empty, it will affect the rendering of the page and you may see blank. Bad for server rendering, in the case of isomorphism, the lifecycle goes to ComponentWillmount, which makes ajax use an error

3. ComponentDidMount component rendering complete

Called after the component has been mounted, and only once globally, within the lifecycle function: 1. 2. After rendering the component for the first time, the DOM node has been generated, you can call ajax request here, and the component will be rendered again after returning setState data

4, componentWillReceiveProps (nextProps)

ComponentWillReceiveProps after accept the parent component change of props need to use more rendering component It accepts a parameter

1. NextProps Compares nextProps and this.props, and sets the nextProps setState to the state of the current component to re-render the component

componentWillReceiveProps (nextProps) { nextProps.openNotice ! = = this. Props. OpenNotice && enclosing setState ({openNotice: nextProps openNotice}, () = > {the console. The log (this. State. OpenNotice: nextProps) / / renew for nextProps state, in the second parameter (the callback) setState can print out the new state})}Copy the code

5, shouldComponentUpdate (nextProps, nextState)

After the component is mounted, shouldComponentUpdate is called every time setState is called to determine if the component needs to be rerendered. The default returns true and requires rerender. Return false and render will not be triggered. In more complex applications, some data changes do not affect the interface display, you can make a judgment here to optimize the rendering efficiency.

Rerendering of the React parent will result in rerendering of all of its children. In this case, we do not need to re-render all of the children, so we need to make decisions in the life cycle of the children

For starters to react, this lifecycle may be less of an opportunity, but if your project starts to focus on performance optimization, you’ll need to use it as you get more comfortable with React

ShouldComponentUpdate (nextProps,nextState){console.log("-- component to accept redrawing state --") if(this.props! = nextProps || this.state ! = nextState) return true }Copy the code

6, componentWillUpdate (nextProps nextState)

ShouldComponentUpdate returns true or after calling forceUpdate, componentWillUpdate is called. Cannot setState in this hook, it will trigger a repeat loop. You can also get the nextProps and nextState here.

7, render function

The Render function inserts the DOM structure generated by JSX. React generates a virtual DOM tree. At each component update, React uses its diff algorithm to compare the old and new DOM trees before and after the update, find the smallest dom nodes that differ, and re-render them

The render function in React16 allows you to return an array, a single string, etc., instead of being limited to a single top-level DOM node, it can reduce the number of unnecessary divs

You can do this now:

Render () {return [<div>< div></div> </div>]}Copy the code

Note: Try not to change state in the Render method as it may trigger an infinite loop that causes stack overflow.

ComponentDidUpdate (prevProps,prevState) Complete component rendering

All render calls componentDidUpdate except for the first time after calling componentDidMount. The setState of this hook may trigger repeated rendering, so you need to judge by yourself, otherwise it will enter an infinite loop.

componentDidUpdate() { if(condition) { this.setState({.. }) // set state} else {// set state}}Copy the code

9, componentWillUnmount ()

Called when a component is uninstalled. Normally events registered in componentDidMount need to be deleted here. Timers like those set in didmount can be cleared in here.

React V16.3 Delete the following three life cycles

1, componentWillMount () components mounted before 2, componentWillReceiveProps (nextProps) props will change before 3, componentWillUpdate (nextProps, NextState) shouldComponentUpdate returns true or after calling forceUpdate, componentWillUpdate is called.

React V16.3 new lifecycle

Static getDerivedStateFromProps triggers after the component is built (after the virtual DOM, before the actual DOM is mounted) and after each new props is fetched. Each time a new props is received, an object is returned as the new state. Returning null means that the state does not need to be updated. Cooperate with componentDidUpdate, can cover all usage of componentWillReceiveProps

Class Example extends React.Component {static getDerivedStateFromProps(nextProps, prevState) {// This is a static}}Copy the code

GetSnapshotBeforeUpdate trigger time: Update occurs after render and before component DOM rendering. Returns a value as the third argument to componentDidUpdate. With componentDidUpdate, you can override all usage of componentWillUpdate.

class Example extends React.Component { getSnapshotBeforeUpdate(prevProps, prevState) { // ... }}Copy the code

A complete life cycle example

class LifeCycle extends React.Component { constructor(props) { super(props); this.state = {str: "hello"}; } componentWillMount() { alert("componentWillMount"); } componentDidMount() { alert("componentDidMount"); } componentWillReceiveProps(nextProps) { alert("componentWillReceiveProps"); } shouldComponentUpdate() { alert("shouldComponentUpdate"); return true; // Return true} componentWillUpdate() {alert("componentWillUpdate"); } componentDidUpdate() { alert("componentDidUpdate"); } componentWillUnmount() { alert("componentWillUnmount"); } render() { alert("render"); return( <div> <span><h2>{parseInt(this.props.num)}</h2></span> <br /> <span><h2>{this.state.str}</h2></span> </div> ); }}Copy the code