useEffect与react生命周期

601 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第4天,点击查看活动详情

一、react 生命后期介绍:

1、创建阶段

  • constructor
  • componentWillMount
  • render
  • componentDidMount
    • 组件挂载到DOM后调用,且只会被调用一次

2、更新阶段

  • componentWillReceiveProps(nextProps)

    • 在该函数(componentWillReceiveProps)中调用 this.setState() 将不会引起第二次渲染。
    • 将props转换成自己的state
    • 此方法只调用于props引起的组件更新过程中,响应 Props 变化之后进行更新的唯一方式
  • shouldComponentUpdate(nextProps, nextState)

    • 每当父组件重新render导致的重传props,子组件将直接跟着重新渲染,无论props是否有变化。可通过shouldComponentUpdate方法优化
    • 此方法通过比较nextProps,nextState及当前组件的this.props,this.state,返回true时当前组件将继续执行更新过程,返回false则当前组件更新停止,以此可用来减少组件的不必要渲染,优化组件性能。
  • componentWillUpdate(nextProps, nextState)

    • 此方法在调用render方法前执行
  • render

  • componentDidUpdate(prevProps, prevState)

    • 适合请求网络获取数据
    • 此方法在组件更新后被调用,可以操作组件更新的DOM,prevProps和prevState这两个参数指的是组件更新前的props和state

3、销毁阶段

  • componentWillUnmount
    • 此方法在组件被卸载前调用

4、错误发生时

  • componentDidCatch(16新添加)

二 、useEffect的使用

1. 模拟componentWillUnmount & componentDidMount

//函数组件中的使用
import React, { useContext, useEffect, useState } from 'react';

export default function Index(props) {
    const [count,setCount] = useState(0)
    useEffect(()=>{
            // 相当于 componentDidMount
            console.log(1)
            return ()=>{
            // 相当于 componentWillUnmount,在这个阶段,该dom节点将销毁,下面的不会打印
                console.log(2)
            }
	    //不打印
            console.log(document.getElementById('btn'),3)
        },[])

}

2. 模拟 componentDidUpdate

import React, { useContext, useEffect, useState } from 'react';

export default function Index(props) {
    const [count,setCount] = useState(0)
    useEffect(()=>{ 
      // 相当于 componentDidUpdate  
      document.getElementById('num').innerHTML = count 
    })
}

3. useEffect的第二个参数

useEffect 第二个参数可以是普通类型、也可以是引用类型。 当页面初次渲染的时候useEffect会被执行,在页面count1变化时,useEffect会被再次出发,类似于 vue中的watch函数,对变量做监听,执行变量的联动操作或者页面数据的刷行

注意:但是不能在 useEffect 中 更新 count1这种监控的变量,不然就会进入一个useEffect的死循环

import React, { useContext, useEffect, useState } from 'react';

export default function Index(props) {
    const [count,setCount] = useState(0)
    useEffect(() => {
        //可以是一些异步接口
        console.log('111)
    }, [count1,count2]);
}

三 、React Hooks :

  • React Hooks只能用于函数组件,而每一次函数组件被渲染,都是一个全新的开始;
  • 每一个全新的开始,所有的局部变量全都重来,全体失忆;
  • 每一次全新的开始,只有Hooks函数(比如useEffect)具有上一次渲染的“记忆”;