1.有些時候我們監(jiān)聽數(shù)據(jù)變化的時候不希望拿到第一次初始化的數(shù)據(jù),這時候我們就需要額外加一個計(jì)數(shù)器,當(dāng)它大于1的時候才去監(jiān)聽
const useUpdate = (dep: boolean, fn: () => void) => {
const [count, setCount] = useState(0)
useEffect(() => {
setCount(x => x + 1)
}, [dep])
useEffect(() => {
if (count > 1) {
fn()
}
}, [count])
}
使用useRef來優(yōu)化
const useUpdate = (dep: boolean, fn: () => void) => {
const isFirst = useRef(true)
useEffect(() => {
if (isFirst.current) {
isFirst.current = false;
return
}
fn()
}, [dep])
}
上面的dep就是我們依賴的數(shù)據(jù),fn就是我們數(shù)據(jù)變化后需要作出的修改