封装useEffect模拟react生命周期

封装useEffect

import {
    
     useEffect } from 'react'

/**
 * 组件挂载后
 * componentDidMount in hook way
 *
 * @export
 * @param {() => any} onMount
 * @returns
 */
export function useOnMount(onMount: () => any) {
    
    
    return useEffect(() => {
    
    
        if (onMount) {
    
    
            //
            onMount()
        }
    })
}

/**
 * 组件卸载后前
 * componentWillUnmount in hook way
 *
 * @export
 * @param {() => any} onUnmount
 * @returns
 */
export function useOnUnmount(onUnmount: () => any) {
    
    
    return useEffect(() => {
    
    
        return () => onUnmount && onUnmount()
    }, [])
}
/**
 * 组件更新前
 * componentDidUpdate in hook way
 *
 * @export
 * @param {() => any} onUpdate
 * @returns
 */
export function useOnUpdate(onUpdate: () => any) {
    
    
    return useEffect(() => {
    
    
        return () => onUpdate && onUpdate()
    })
}

关于react18当主键挂载后会调用两次的问题
发送了两次请求
在这里插入图片描述
在这里插入图片描述
去掉StrictMode,就不会发送两次请求了
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_47287832/article/details/128502241