React穷举deps规则标记自定义挂钩中缺少的依赖项



免责声明:我搜索了SO,发现这个问题与我的问题非常接近,但我并没有完全理解唯一的答案。我添加了一个帖子来要求更多的解释(我不能添加评论,因为我缺乏声誉(,但它被删除了,因为它不是一个答案,因此我被迫在这里创建新的线程

我需要一些关于exhaustive-deps规则的解释。我想我错过了什么。

谢谢你的灯!:(

React文档指出:

React保证setState函数标识是稳定的,并且在重新渲染时不会更改。这就是为什么从useEffect或useCallback依赖项列表中省略是安全的。

(来源(

然而,考虑一下:

import { useEffect, useState } from 'react';
// Writing a custom hook that only calls `useState` and returns what `useState` returns
const useMyOwnStateHook = initialValue => useState(initialValue);
const MyComponent = () => {
// Here we have a direct call to `useState`
const [, setStandardState] = useState('');
// Here we call `useState` in our hook
const [, setMyOwnState] = useMyOwnStateHook('');
useEffect(() => {
// This call is safe and does not raise any linting error, as per the doc (https://reactjs.org/docs/hooks-reference.html#usestate)
setStandardState('');
// This call triggers the following error in the console:
// Line 19:6:  React Hook useEffect has a missing dependency: 'setMyOwnState'. Either include it
// or remove the dependency array  react-hooks/exhaustive-deps
setMyOwnState('');
}, []);
return <span></span>
};
export default MyComponent;

在这里,我不明白为什么对setStandardStatesetMyOwnState的调用都不安全。我的代码中到处都有这样的依赖项,这确实给我的useEffect的依赖数组带来了负担,我很想了解如何摆脱它们:-(

我在package.json中使用以下版本的React:

"react": "^17.0.2",
"react-scripts": "4.0.3",

谢谢你抽出时间!

如果setMyOwnState在渲染之间没有变化(就像setState函数一样(,您可以简单地将其列为依赖项,而不必担心它会导致任何不必要的副作用,因为它永远不会改变
这就是react-redux如何使用其useDispatch挂钩处理相同问题

如果setMyOwnState可以在渲染之间更改,那么react会警告您有关它的是有道理的

相关内容

最新更新