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

      

  • 相关阅读:
    noip模拟赛(一)宠物之战
    noip模拟赛(一)魔法树
    luogu1097统计数字[noip2007提高组Day1T1]
    luogu1207双重回文数[usaco1.2]Dual Palindromes
    【2018.9.20】JOI 2017 Final T3「JOIOI 王国 / The Kingdom of JOIOI」
    【2018.9.20】JOI 2017 Final T2「準急電車 / Semiexpress」
    Codeforces Round #510
    【2018.9.15】陈老师模拟赛1
    【loj6191】「美团 CodeM 复赛」配对游戏
    【loj6029】「雅礼集训 2017 Day1」市场
  • 原文地址:https://www.cnblogs.com/Mr-Rshare/p/13564153.html
Copyright © 2020-2023  润新知