繁体   English   中英

解决 React useEffect hook 中的位置依赖警告

[英]Resolve location dependency warning in React useEffect hook

我有一个useEffect ,我只想在 React 组件中第一次执行。 我在useEffect中使用location.pathname ,如果我将数组依赖项留空,我会收到此警告:

React Hook useEffect has a missing dependency: 'location.pathname'. Either include it or remove the dependency array.eslintreact-hooks/exhaustive-deps

如果我包含依赖项,则每次用户导航时都会执行useEffect

我看到很多人说这个警告只是一个潜在的问题,但如果你知道自己在做什么,你可以简单地忽略它,或者使用// eslint-disable-line react-hooks/exhaustive-deps禁用警告。

我一直在阅读这个问题,我知道对于函数我应该使用useCallback 这种情况的等价物是什么?


import { useLocation } from 'react-router-dom';

// Inside component

  const location = useLocation();
  useEffect(() => {
    if (location.pathname === VIEWS.initial) {
      setChecked(false);
    }
  }, []);

这个问题最正确的解决方案是什么?

我建议在useState而不是useEffect中设置初始值:

const location = useLocation();
const [checked, setChecked] = useState(location.pathname === VIEWS.initial)

如果您真的想通过useEffect将 state 设置为挂载,最不冗长的替代方法是通过注释抑制警告。 但是,如果您稍后使用更多逻辑扩展此效果,您将面临遇到有关此警告可能已阻止的陈旧数据的神秘错误的风险。

第三种方法是确保效果仅运行一次,同时保持location.pathname依赖性:

  const [hasMounted, setHasMounted] = useState(false)
  const location = useLocation();

  useEffect(() => {
    if (!hasMounted && location.pathname === VIEWS.initial) {
      setChecked(false);
      setHasMounted(true);
    }
  }, [location.pathname, hasMounted]);

与我的第一个建议相比,我认为这是不可取的,因为可读性差且不必要的复杂性。

useRef解决。 看起来工作正常,警告消失了:

import { useLocation } from 'react-router-dom';
import { useRef } from 'react';

// Inside component

  const location = useLocation();
  const initialView = useRef(location.pathname);

  useEffect(() => {
    if (initialView.current === VIEWS.initial) {
      setChecked(false);
    }
  }, []);
const location = useLocation();
  useEffect(() => {
    
    if ((location.pathname)&&location.pathname === VIEWS.initial) {
      setChecked(false);
    }
  }, []);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM