如何配置 eslint 规则以在全局范围内忽略 react-hooks/exhaustive-deps?

mas*_*hef 4 typescript reactjs eslint eslintrc typescript-eslint

我有一个带有 useEffect 钩子的 react 组件,如下所示:

const LocationEditor: React.FC<SectionEditorProps> = (props) => {
const [section, setSection] = useState({...(props.section as Location)});
useEffect(() => {
    props.onChange(section);
}, [section]);
Run Code Online (Sandbox Code Playgroud)

我在运行项目时收到此警告:

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
Run Code Online (Sandbox Code Playgroud)

所以我尝试将组件更改为如下所示,解构道具:

const LocationEditor: React.FC<SectionEditorProps> = ({section, onClickCancel, onClickSave, onChange}) => {
    const [tmpSection, setSection] = useState({...(section as Location)});
    useEffect(() => {
        onChange(tmpSection);      
    }, [tmpSection]);
Run Code Online (Sandbox Code Playgroud)

如果我在依赖数组之前添加此注释,我可以使警告消失:

// eslint-disable-next-line react-hooks/exhaustive-deps
Run Code Online (Sandbox Code Playgroud)

但是,当我将下面的块添加到它时eslintConfigpackage.json它似乎没有做任何事情:

{
  "plugins": [
    "react-hooks"
  ],
  "rules": {
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "off"
  }
}
Run Code Online (Sandbox Code Playgroud)

我看到有些人在谈论使用该.eslinrc文件,但我认为您也可以在其中全局配置规则,但我package.json在我的项目中找不到该文件。

有什么我在这里想念的吗?

Obe*_*ano 8

不要禁用。该规则已经过测试和重新测试,并且与任何其他 ESLint 规则相比,即使不是更多,也是战斗伤痕累累和被探索的。

我也是,以为我知道得更好。但我们都没有。不要禁用它,相信我,它比你我更了解。我也去过那里。

只需按照规则进行操作,如果它破坏了您的应用程序,请高兴,因为它免费为您找到了一个错误,您应该修复它,而不是强迫您的应用程序运行。

  • “按照规则去做”——这并不总是最好的选择。举个例子:如果你需要从服务器获取数据,你通常会向 useEffect 传递一个空数组作为第二个参数(因为你只需要在组件挂载时运行回调一次)——这是 React 文档的官方建议。然后,“exhaustive-deps”经常会开始警告您“忘记”依赖项(但您确定您没有忘记),从而惹恼您。添加不需要的依赖项是一种反模式,因为它可能会导致不必要的重新渲染,甚至导致无限的重新渲染循环...... (61认同)
  • 我认为这只是部分正确。实际上,useState 的官方文档说从依赖数组中省略 setter 是安全的。https://reactjs.org/docs/hooks-reference.html#usestate 也许期望 linter 识别出未包含在依赖项数组中的 setter 或 useReducer-dispatch 函数是太过分了? (4认同)