React学习笔记(六)--自定义Hook 之 useUpdate

202 阅读1分钟

自定义useUpdate的原因是因为 seEffect 会在一开始变量为undefined 变成 我们赋予的值时候会触发该事件

const useUpdate = (fn,dep) =>{
    const [count, setCount] = useState(0)
    useEffect(()=>{
        setCount(x=>x+1)
    },[dep])

    useEffect(()=>{
        if(count>1){
            fn()
        }
    },[count,fn])
}
//调用 
useUpdate(()=>{
    console.log('变了')
},n)