1. 程式人生 > 實用技巧 >react hook 使用注意點

react hook 使用注意點

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])