这个问题在这里已经有了答案:
Understanding the React Hooks 'exhaustive-deps' lint rule
(2 个回答)
9 个月前关闭。
我有一个带有 useEffect 钩子(Hook)的 react 组件,如下所示:
const LocationEditor: React.FC<SectionEditorProps> = (props) => {
const [section, setSection] = useState({...(props.section as Location)});
useEffect(() => {
props.onChange(section);
}, [section]);
我在运行项目时收到此警告:React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect react-hooks/exhaustive-deps
所以我尝试将组件更改为如下所示,解构 Prop :const LocationEditor: React.FC<SectionEditorProps> = ({section, onClickCancel, onClickSave, onChange}) => {
const [tmpSection, setSection] = useState({...(section as Location)});
useEffect(() => {
onChange(tmpSection);
}, [tmpSection]);
如果我在依赖数组之前添加此注释,我可以使警告消失:// eslint-disable-next-line react-hooks/exhaustive-deps
但是,当我将下面的块添加到 eslintConfig
时在 package.json
它似乎没有做任何事情:{
"plugins": [
"react-hooks"
],
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "off"
}
}
我看到有些人在谈论使用 .eslinrc
文件,但我认为您也可以在 package.json
中全局配置规则我在我的项目中找不到那个文件。有什么我在这里想念的吗?
最佳答案
不要禁用。该规则已经过测试和重新测试,并且与任何其他 ESLint 规则相比,即使不是更多,也是战斗伤痕累累和被探索的。
我也是,以为我知道得更好。但我们都没有。不要禁用它,相信我,它比你我更了解。我也去过那里。
只需按照规则进行操作,如果它破坏了您的应用程序,请高兴,因为它免费为您找到了一个错误,您应该修复它,而不是强制您的应用程序运行。
关于reactjs - 如何配置 eslint 规则以在全局范围内忽略 react-hooks/exhaustive-deps?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65704653/