1.useEffect
useEffect執行環境:
// componentDidMount useEffect(() => { // do something }, []) // componentUpdate count變量更新時執行 useEffect(() => { // do something }, [count]) // componentWillUnmount useEffect(() => { console.log('進入'); return () => { console.log('離開'); } },[])
2. 當在useEffect 使用 變量或者函數,並且沒有添加依賴時, 會報如下錯誤
錯誤:React Hook useEffect has missing dependencies: 'fn1' and 'menuList'. Either include them or remove the dependency array
const fn1 = (list) => { let hashMap = new Map(); fn2(list, hashMap); return hashMap.get(location.pathname); } const fn2 = (list, map) => { list.forEach(item => { map.set(item.path, item.id) if(item.children && item.children.length > 0){ mapList(item.children, map); } }); } useEffect(() => { fn1(menuList); },[])
變量的話直接添加到以來的數組里即可,函數的話添加到依賴數組后會報這個警告
The 'fn1' function makes the dependencies of useEffect Hook (at line 208) change on every render. Move it inside the useEffect callback. Alternatively, wrap the 'fn1' definition into its own useCallback() Hook;
解決辦法: 使用useCallback
注意:
1. 使用useCallback時,函數中使用到的變量也需要添加到依賴的數組中
2. 使用useCallback時,函數中調用另外一個函數時,需在當前函數前聲明
const fn2 = useCallback((list, map) => { list.forEach(item => { map.set(item.path, item.id) if(item.children && item.children.length > 0){ mapList(item.children, map); } }); },[])
const fn1 = useCallback((list) => { let hashMap = new Map(); mapList(list, hashMap); return hashMap.get(location.pathname); },[location, mapList])
useEffect(() => { let path = findNowPath(menuList).toString(); setSelectedKeys([path]) },[menuList, findNowPath])