React - understanding and use of useEffect function

One, useEffect description

We know that there is no life cycle in the function component of react, and there is no state. There is no state that can be used useStateas a substitute, so what about the life cycle?

useEffectis react v16.8a newly introduced feature. We can think of the useEffect hook as a combination of the three life cycles of componentDidMount, componentDidUpdate, and componentWillUnmount. Allows you to perform some side effects in functional components;

Common side effects include:

  1. send ajax request
  2. Set Subscription/Start Timer
  3. Manually change the real DOM

Second, its execution timing

It can be regarded as a combination of these three life cycle functions, that is, it will be executed at these three times

componentDidMount (component has been mounted)

componentDidUpdate (component has been updated)

componentWillUnmount (the component is about to be unmounted)

Three, useEffect is used according to the situation

useEffect()There are two parameters: the first parameter is the callback function to be executed, the second parameter is an array of dependency arrays (the second parameter can be filled in according to the requirements), and whether to execute the function is determined according to whether the variables in the array change ;

Let’s take a look at the following simple case first, and then discuss it according to the situation:

useEffect.js

import React, {
    
     useState, useEffect, useRef } from "react";

// 类型约定
interface interList {
    
    
  id: number | string; // 类型可能是number也可能是string
  text: string;
  done: boolean;
}
// 渲染数据
const myList: Array<interList> = [
  {
    
     id: 0, text: "参观卡夫卡博物馆", done: true },
  {
    
     id: 1, text: "看木偶戏", done: true },
  {
    
     id: 2, text: "打卡列侬墙", done: true }
];

const UseEffect: React.FC = (props: any) => {
    
    
  let [num, setNum] = useState(100);
  let [useInfo, SetUserInfo] = useState(myList);

   // 0,什么都不传 就是监听所有数据的变化
   useEffect(() => {
    
    
    console.log("我改变了-all");
  }); 

  // 1,此处相当于 componentDidUpdate生命周期 组件已经更新完成
  useEffect(() => {
    
    
    console.log("我改变了");
  }, [num]); // 只监听num的变化,useInfo的变化不会被监听到

  // 2,此处相当于componentDidMount生命周期 组件已经挂载完成
  useEffect(() => {
    
    
    console.log("componentDidMount");
    console.log("可以拿到num的值:", num);
  }, []);

  // 3,此处相当于 componentWillUnmount生命周期 组件即将卸载
  useEffect(() => {
    
    
    // 返回一个回调函数
    return () => {
    
    
      console.log("组件将要卸载了");
    };
  }, []);

  // 其实传不传空数组或不是空数组,useEffect函数里面的回调都会执行一次,也就是说componentWillUnmount这个生命周期页面进来就会执行
  // useEffect 这个hoosk也是可以写多个的,尽量不同的处理写在不同useEffect里面

  // 点击改变用户信息
  const change = () => {
    
    
    // react 建议不要更改原数组 返回一个数组的拷贝
    const newList = [...useInfo, {
    
     id: 3, text: "优菈", done: false }];
    SetUserInfo(newList);
  };

  // 点击加一
  const add = () => {
    
    
    setNum(++num);
  };

  const lis = useInfo.map((item, index) => {
    
    
    return (
      <li key={
    
    index}>
        {
    
    index}:{
    
    item.text}
      </li>
    );
  });

  return (
    <>
      <div>
        <h3>userEffect 副作用hooks函数</h3>
        <br />
        <button onClick={
    
    add}>点击加一</button>
        <p>{
    
    num}</p>
        <br />
        <button onClick={
    
    change}>改变用户信息</button>
        <ul>{
    
    lis}</ul>
      </div>
    </>
  );
};
export default UseEffect;

Renderings:
insert image description here

The effect achieved by the above code is very simple. The two buttons change the state of their respective data respectively. The state change will trigger the useEffecexecution of the t function. The second parameter parameter affects the change of this function, so the following is a case-by-case discussion:

1. Do not write the second parameter to indicate that all states are monitored, and one of the changes will trigger this function

If the second parameter is not written, the function operation will monitor useEffect(method)all states every time, which is equivalent to componentDidUpdate the life cycle - the component has been updated.

   import {
    
    useEffect } from "react";
   useEffect(() => {
    
    
    console.log("我改变了-all");
  }); // 监听所有数据的变化

2. If the second parameter is []an empty array, it means no one monitors

If the second parameter is []an empty array, it means that no one will monitor it, and useEffect回调函数the function at this time is equivalent to
componentDidMount the life cycle - the component has been mounted;

  // 2,此处相当于componentDidMount生命周期 组件已经挂载完成
  useEffect(() => {
    
    
    console.log("componentDidMount");
    console.log("可以拿到num的值:", num);
  }, []);

3. If the second parameter only passes the state that needs to be monitored, the function will only be executed according to this state

If the array in the second parameter is only passed num, it means that numthis useEffectcallback function will be triggered only when it changes, which is equivalent to monitoring this data.

  // 1,此处相当于 componentDidUpdate生命周期 组件已经更新完成
  useEffect(() => {
    
    
    console.log("num改变了");
  }, [num]); // 只监听num的变化

Of course, multiple ( ) can also be written in the array [num,userInfo], and multiple data changes can be monitored at the same time.

4. Return a callback function in useEffect, which is equivalent to the life cycle of the component about to be unloaded

What does this sentence mean?
Usually, a component has an unloaded life cycle. To use it, you useEffect 函数only need to return a callback function in it. This callback function is equivalent tocomponentWillUnmount the declaration cycle, and you can clear resources such as created subscriptions or timer IDs in it.

  // 3,此处相当于 componentWillUnmount生命周期 组件即将卸载
  useEffect(() => {
    
    
    // 返回一个回调函数
    return () => {
    
    
      console.log("组件将要卸载了");
    };
  }, []);

Passing an empty array here means that I don't want to monitor data changes, but only want to execute the logic when the component is uninstalled;

5. Pay attention

In fact, whether the second pass is an empty array or not, the callback in the useEffect function will be executed once, that is to say, componentWillUnmountthis life cycle will be executed automatically when the page comes in;

useEffect函数This hoosk can also be written in multiples, try to write different business processes in different useEffects;

Guess you like

Origin blog.csdn.net/qq_43886365/article/details/132225206