我有一个关于 eslint-plugin-react-hooks 的问题。
我想减少执行 API 调用并将结果存储到状态中的样板代码,因此我创建了一个自定义挂钩:
export const loading = Symbol('Api Loading');
export const responseError = Symbol('Api Error');
export function useApi<T>(
apiCall: () => CancelablePromise<T>,
deps: DependencyList
): T | (typeof loading) | (typeof responseError) {
const [response, setResponse] = useState<T | (typeof loading) | (typeof responseError)>(loading);
useEffect(() => {
const cancelablePromise = apiCall();
cancelablePromise.promise
.then(r => setResponse(r))
.catch(e => {
console.error(e);
setResponse(responseError);
});
return () => cancelablePromise.cancel();
}, deps); // React Hook useEffect has a missing dependency: 'apiCall'. Either include it or remove the dependency array. If 'apiCall' changes too often, find the parent component that defines it and wrap that definition in useCallback (react-hooks/exhaustive-deps)
return response;
}
现在自定义钩子效果很好,但 eslint-plugin-react-hooks 没有那么多。我的代码中的警告不是一个大问题。我知道我可以通过添加评论来消除此警告:
// eslint-disable-next-line react-hooks/exhaustive-deps
问题是自定义钩子参数之一是依赖列表,而 eslint-plugin-react-hooks 不会检测到缺少的依赖项。如何让 eslint-plugin-react-hooks 正确检测自定义挂钩的依赖项列表问题?甚至可以对自定义钩子进行这种检测吗?