封装自定义 Hooks - 生命周期 hooks
//life-cycle.js
import { useEffect, useRef } from "react";
//componentDidMount
function useMount(fn) {
useEffect(() => { fn() }, [])
}
//componentDidUpdate
function useUpdate(fn) {
const mounting = useRef(true)
useEffect(() => {
if (mounting.current) {
mounting.current = false;
} else {
fn();
}
})
}
//componentUnMount
function useUnMount(fn) {
useEffect(() => fn(), [])
}
export {
useMount,
useUpdate,
useUnMount
}
在 function 组件中使用
import { useState } from 'react';
import * as hookLife from "../../hooks/life-cycle";
function List(props) {
let forceUpdate = useState(0)[1];
hookLife.useMount(() => {
console.log("did mount!")
})
hookLife.useUpdate(() => {
console.log("did update!")
})
hookLife.useUnMount(() => {
console.log("did unmount!")
})
return (
<div>
<p>
<button onClick={forceUpdate}>强制刷新</button>
</p>
</div>
)
}
export default List;
网友评论