- 由于Function组件内没有组件的生命周期,那我们可以依赖useEffect封装一套自己的生命周期函数
1.useMount
import { useEffect, EffectCallback } from 'react'
export const useMount = (callback: EffectCallback) => {
useEffect(callback, [])
}
调用方式
import { useMount } from './hooks'
const DemoComponent = () => {
useMount(() => {
console.log('组件挂载了')
})
}
2.useUnmount
import { useEffect, EffectCallback } from 'react'
export useUnmount = (callback: EffectCallback) => {
useEffect(() => () => callback(), [])
}
import { useUnmount } from './hooks'
const DemoComponent = () => {
useUnmount(() => {
console.log('组件卸载了')
})
}
3.useUpdate
import { useEffect, EffectCallback, useState } from 'react'