警告:React Hook useEffect has a missing dependency

Elysian
2021-08-28 / 0 评论 / 262 阅读 / 正在检测是否收录...

问题

在使用useEffect时,当我们将函数的声明放在useEffect函数外面时,会报eslint警告

webpackHotDevClient.js:119 ./src/pages/detail/enterprise/modules/businessWarning/modules/tendAndBid/modules/topTitle/index.jsx
  Line 27:6:  React Hook useEffect has a missing dependency: 'menuConfig'. Either include it or remove the dependency array. You can also do a functional update 'setMenuConfig(m => ...)' if you only need 'menuConfig' in the 'setMenuConfig' call  react-hooks/exhaustive-deps

解决办法

1.使用 // eslint-disable-line react-hooks/exhaustive-deps

useEffect(() => {
    clickshow()
  }, [showConfirmation])// eslint-disable-line react-hooks/exhaustive-deps

  function clickshow() {
    if (showConfirmation) {
      document.addEventListener('click', isShowConfir, true);
    } else {
      document.removeEventListener('click', isShowConfir, true);
    }
  }

  function isShowConfir(e) {
    if (showConfirmation) {
      let _con = confDom.current;
      if (_con && !_con.contains(e.target)) {
        e.stopPropagation();
        setShowConfirmation(false)
      }
    }
  }

2.将函数 放在useEffect内

useEffect(() => {
    function clickshow() {
      if (showConfirmation) {
        document.addEventListener('click', isShowConfir, true);
      } else {
        document.removeEventListener('click', isShowConfir, true);
      }
    }


    function isShowConfir(e) {
      if (showConfirmation) {
        let _con = confDom.current;
        if (_con && !_con.contains(e.target)) {
          e.stopPropagation();
          setShowConfirmation(false)
        }
      }
    }
    clickshow()
  }, [showConfirmation])

总结

以上两种方式可以解决useEffect警告,类似useCallback等警告也可以通过方法1解决。

0

评论

博主关闭了所有页面的评论