是函數(shù)組件中執(zhí)行的副作用,副作用就是指每次組件更新都會執(zhí)行的函數(shù),可以用來取代生命周期。
1. 基本用法
import { useEffect } from "react";
useEffect(()=>{
console.log('副作用');
});
2. 副作用分為需要清除的和不需要清除
假如設(shè)置一個定時器,當(dāng)組件卸載時需要將定時器關(guān)閉,這就是需要清除的。
需要清除的需要在副作用中返回一個函數(shù)即可,返回的函數(shù)編寫需要的代碼邏輯。
import { useEffect } from "react";
useEffect(()=>{
return () => {
console.log('執(zhí)行代碼邏輯');
}
});
不需要清除的就是正常的。
3. 傳入第二個參數(shù)
不傳入,則組件更新時就會執(zhí)行。
傳入空數(shù)組[]
則代表只運行一次(僅在組件掛載和卸載時執(zhí)行),當(dāng)副作用沒有返回函數(shù)時可以當(dāng)做生命周期componentDidMount使用,返回函數(shù)時可以當(dāng)做生命周期componentWillUnmount使用
// 當(dāng)做 componentDidMount使用
import { useEffect } from "react";
useEffect(()=>{
console.log('頁面渲染完成');
}, []);
// 當(dāng)做 componentWillUnmount使用
import { useEffect } from "react";
useEffect(()=>{
return () => {
console.log('組件卸載');
}
}, []);
- 傳入數(shù)組 [item]
import { useEffect, useState } from "react";
const [ count, setCount ] = useEffect(1);
useEffect(()=>{
console.log('執(zhí)行了');
}, [count]);
當(dāng)數(shù)組不為空時,組件更新時,會檢測count的值,若更新后的值與舊值不一樣則會調(diào)用effect,若相同則會跳過執(zhí)行。
若數(shù)組傳入多個參數(shù),只要有一項有變更就會執(zhí)行effect。