The life cycle

mount

  • constructor

To set the initial value of the component, or to change the this operation, use the super keyword first and inherit the superclass to avoid errors

constructor () {
    super(a);// Initialization state
    this.state = {
        const
    }
    // Change this operation
    this.handoler = this.handoler.bind(this)}Copy the code
  • render

The purpose is to parse JSX, and then display it on the interface

render () {
  return (
  	<div ref="name"></div>)}Copy the code
  • componentDidMount

After the component is mounted, network requests can be made internally, timers can be customized, event listeners can be added, DOM elements can be obtained and so on

componentDidMount () {
 	const text = this.refs.name.textContent
    console.log(text);
}
Copy the code

update

When the data changes and the component needs to be re-rendered, the data update includes the data passing through the props, or the internal data (state) of the component itself, the component will update automatically

  • shouldComponentUpdate

This is used to set the component to update. This returns true by default, false, and the following methods do not update

parameter

Parameter one accepts the value in props

Parameter two receives the state value of the current component

PS: Receive parameters are used to determine whether the current component needs to be re-rendered.

If the parent component is updated, the child component will also be updated, but the internal data of the child component is not updated, is reloaded, all Settings. Determine if the current component needs to be rerendered

shouldComponentUpdate (nextProps,nextState) {
    if (nextState.const === this.state.const) {
      return false
    }
    return true
}
Copy the code

PS: The parameter obtains the latest data, and determines whether it needs to be updated by judging the data

PS: In the latest version of REACR, this method is not recommended. Instead, it is recommended to inherit a new parent class to perform operations as needed

class App extends PureComponent {}Copy the code
  • Render, componentDidUpdate

Methods are the same as the last two mounted methods, especially componentDidUpdate, which executes internal code when the data is updated

uninstall

When a component is switched to another component, the previous component is unloaded, but the internal execution event operation still exists, wasting memory, so before the component is unloaded, the method is executed

  • componentWillUnmount
 // Remove unnecessary events before component uninstallation
 componentWillUnmount () {
   window.removeEventListener('click'.this.foo)
 }
Copy the code