一、參數規則
1、可選的
2、數組類型
3、值為state或者props
二、不同的參數和返回
1、不傳參數
默認的行為,會每次 render 后都執行,一般表單控制中使用
類似於類組件中的componentDidMoount以及componentDidUpdate
useEffect(() => { console.log('useEffect with no dependency') })
2、空數組
傳入第二個參數,每次 render 后比較數組的值沒變化,不會在執行
類似於類組件中的 componentDidMount
useEffect(() => { console.log('useEffect with empty dependency') }, [])
3、有一個或者多個值得數組
傳入第二個參數,只有一個值,比較該值有變化就執行,
傳入第二個參數,有2個值的數組,會比較每一個值,有一個不相等就執行
類似於類組件中的componentDidUpdate
useEffect(() => { console.log('useEffect widh specify dependency') }, [state, props])
4、返回一個函數
返回時傳遞一個函數進行卸載,在組件卸載時候調用
類似於類組價中componentWillUnmout
useEffect(() => { console.log('useEffect widh specify callback');
return () => {
console.log('useEffect with specify callback');
}
})