【发布时间】:2020-05-22 15:15:31
【问题描述】:
我有一个关于 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 正确检测自定义挂钩的依赖列表问题? 甚至可以对自定义钩子进行这种检测吗?
【问题讨论】:
-
为什么不能将apiCall作为依赖传入? (无论如何,它是从哪里来的?)如果该函数经常更改(这看起来很奇怪),您可以按照建议使用 useCallback 来记住它吗?
标签: reactjs react-hooks eslint eslint-plugin-react-hooks