React生命周期函数

2020-09-21  本文已影响0人  kevin5979
生命周期
  1. 每挂载一个组件,会先执行constructor构造方法来创建组件
  2. 紧接着调用render函数,获取要渲染的DOM结构(jsx),并且开始渲染DOM
  3. 当组件挂载成功(DOM渲染完成),会执行componentDidMount生命周期函数
  1. 当我们通过修改props,或者调用setState修改内部状态,或者直接调用forceUpdate时会重新调用render函数,进行更新操作
  2. 当更新完成时,会回调componentDidUpdate生命周期函数
  1. 当我们的组件不再使用,会被从DOM中移除掉(卸载)
  2. 这个时候会回调componentWillUnmount生命周期函数

constructor(props)

componentDidMount()

componentDidUpdate(prevProps, prevState, snapshot)

componentDidUpdate(prevProps) {
  // 典型用法(不要忘记比较 props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

componentWillUnmount()

验证生命周期函数

import React, { Component } from 'react';

class TestCpn extends Component {
  render() {
    return <h2>TestCpn</h2>
  }
  componentWillUnmount() {
    console.log("组件卸载完成 ----- TestCpn componentWillUnmount");
  }
}

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    }
    console.log("调用constructor方法");
  }

  render() {
    console.log("调用render方法")
    return (
      <div>
        <h2>当前计数: {this.state.counter}</h2>
        {/* this.state.counter > 5, 卸载TestCpn组件 */}
        {this.state.counter <= 5 && <TestCpn/>}
        <button onClick={e => this.increment()}>+1</button>
      </div>
    )
  }

  increment() {
    this.setState({
      counter: this.state.counter + 1
    })
  }

  componentDidMount() {
    console.log("组件挂载完成 ----- 调用componentDidMount方法");
  }

  componentDidUpdate() {
    console.log("更新数据完成 ----- 调用componentDidUpdate方法");
  }

  componentWillUnmount() {
    console.log("组件卸载完成 ----- 调用componentWillUnmount方法");
  }
}
image.png END
上一篇 下一篇

猜你喜欢

热点阅读