React 类组件生命周期概述

138 阅读1分钟

类组件

zh-hans.reactjs.org/docs/react-…

  • 挂载阶段

    1. constructor()
    2. static getDerivedStatefromProps()
    3. render()
    4. componentDidMount()
  • 更新阶段

    1. static getDerivedStatefromProps()
    2. shouldComponentUpdate()
    3. render()
    4. getSnapshotBeforeUpdate()
    5. componentDidUpdate()
  • 卸载阶段

    1. componentWillUnmount()
  • 错误处理

    1. static getDerivedStateFromError()
    2. componentDidCatch()
  • 其他API

    1. setState()
    2. forceUpdate()
  • class属性

    1. defaultProps
    2. displayName
  • 实例属性

    1. props
    2. state

iShot2022-04-26_11.35.34.png

class DemoClass extends React.Component {
  // 唯一修改state的地方
  constructor(props) {
    super(props)
    // 私有属性:可变
    this.state = {
      counter: 100,
    }
  }
  
  componentDidMount() {
    // 在渲染过程中只执行一次。监听事件、获取DOM、请求数据等
  }
  
  shouldComponentUpdate(nextProps, nextState) {
    return true
  }
  
  componentDidUpdate(prevProps, prevState, snapshot) {
    // 判断参数是否变化,变化就调用请求函数重新请求数据
    console.log(this.props === prevProps)
  }
  
  componentWillUnmount() {
    // 清理定时器、取消网络请求、取消时间监听等
  }
  
  handleClick() {
    this.setState((state, props) => ({
      counter: state.counter + 1
    }), () => {
      // callback回调,可及时拿到已更改的state
    })
  }
  
  render() {
    return (
      <div>
        <p>{ this.state.counter }</p>
        <Button onClick={ () => handleClick() }>按钮</Button>
      </div>
    )
  }
}