【React全解2】React生命周期函数含义及使用

1,426 阅读3分钟

目录

  • 生命周期
  • 函数列表
  • 重要生命周期函数细解
  • 分阶段看钩子的执行顺序(图解)

一、生命周期

生命周期就是指一个对象的生老病死。

React中就特指一个组件的“生老病死”。

二、函数列表

  1. constructor() -- 初始化 state 等
  2. static getDerivedStateFromProps()
  3. shouldComponentUpdate()&React.PureComponent -- 是否进行更新
  4. render() -- 创建虚拟 DOM
  5. getSnapshotBeforeUpdate
  6. componentDidMount() -- 组件已出现在页面
  7. componentDidUpdate() -- 组件已更新
  8. componentDidWillUnmount() -- 组件将死
  9. static getDerivedStateFromError()
  10. componentDidCatch()

三、重要生命周期函数细解

1、constructor

  • 参数
constructor(props);
  • 用途
  1. 初始化 props
  2. 初始化 state,但此时不能调用setState
  3. 用来写bind this
constructor(){
	/* 省略不必要的代码 */
	this.onclick=this.onclick.bind(this)
}
// 可用以下新语法代替
constructor(){
	/* 省略其他不必要的代码 */
}
onclick=()=>{}
  1. 可不写,但写了就必须写全

2、shouldComponentUpdate

  • 参数
shouldComponentUpdate(nextProps, nextState)
# next就是new => 就是新的数据
  • 作用

    它允许我们手动判断是否要进行组件更新,我们可以根据应用场景灵活设置返回值,以避免不必要的更新。

  • 用途

  1. 返回 true 表示让 UI 更新
  2. 返回 false 表示阻止 UI 更新
  3. 将newState的每个属性和this.state作对比,某个不等就更新,否则不更新。
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      n: 1,
    };
  }
  shouldComponentUpdate(newProps, newState) {
    if (newState.n === this.state.n) {
      return false;
    } else {
      return true;
    }
  }
}
  1. React.PureComponent:这个是上面自己判断是否要更新的语法糖,如果继承的是 React.PureComponent 而不是 React.Component。那么它会自己判断是否需要更新(还是通过数据是否变化)

3、render

  • 用途
  1. 展示视图 return(<div>....</div>)
  2. 写的 HTML 只要一个根元素
  3. 如果 HTML 有多个根元素,需要用<React.Fragment></React.Fragment>包起来,可以缩写为<></>
  • 技巧
  1. render 里面可以写if...else语句
  2. render 里面可以写?:表达式
  3. render 里面不能直接写for循环,要用数组
  4. render 里面可以写 array.map(循环)

4、componentDidMount

  • 参数
componentDidMount();
  • 用途
  1. 在元素插入页面后执行代码,这些代码依赖 DOM
  2. 此处可以发起加载数据的AJAX请求(官方推荐)
  3. 首次渲染会执行此钩子
  4. 你如果想获取 div 的高度,最好在这里写

5、componentDidUpdated

  • 参数
componentDidUpdate(prevProps, prevState, snapshot);
  • 用途
  1. 在视图更新后执行代码
  2. 此处也可发起 AJAX 请求,用于更新数据
  3. 首次渲染不会执行此钩子
  4. 在此处setState可能会引起死循环(除了判断条件后)
  5. 若 shouldComponentUpdated()返回 false,则不会触发此钩子

6、componentWillUnmount

  • 参数
componentWillUnmount();
  • 用途
  1. 组件将要被移除页面然后被销毁时执行的代码
  2. unmount过的组件不会再次mount
  • 注意事项

    如果你在组件componentDidMount中创建监听事件,计时器,AJAX请求等等。那么你就要在该组件componentWillUnmount中取消监听事件,计时器AJAX请求等等

    原则:处理不必要的垃圾内存!

四、分阶段看钩子的执行顺序