[英]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.