React 上下文函数的正确类型声明是什么以避免 linting 问题?



我正在使用React Context,并且我有:

const DocumentContext = createContext<
[DocumentStateType, React.Dispatch<any>, React.Dispatch<any>]
>([initVal, () => { }, () => { }]);

但我的门楣抱怨道:

Unexpected empty arrow function @typescript-eslint/no-empty-function

我知道我可以在我的过梁设置中关闭它,但有正确的方法吗?

如果您只想抑制linter消息,您可以将其声明为:

const DocumentContext = createContext<
[DocumentStateType, React.Dispatch<any>, React.Dispatch<any>]
>([initVal, () => { /* do nothing */ }, () => { /* do nothing */ }]);

或作为:

const DocumentContext = createContext<
[DocumentStateType, React.Dispatch<any>, React.Dispatch<any>]
>([initVal, () => undefined, () => undefined]);

如果你绝对确定你不会在任何地方使用这个默认值。即,除了上下文的提供者之外,您没有使用该上下文的组件,您可以简单地将其定义为:

const DocumentContext = createContext<
[DocumentStateType, React.Dispatch<any>, React.Dispatch<any>]
>(null as any);

您可以使用选项allowArrowFunctions

文档

"@typescript-eslint/no-empty-function": ["error", {"allow": ["arrowFunctions"]}],

如果使用lodash,可以使用noop函数绕过linting。

我认为其他库也有类似的功能

最新更新