gpt4 book ai didi

reactjs - 带有依赖列表和 eslint-plugin-react-hooks 的自定义钩子(Hook)

转载 作者:行者123 更新时间:2023-12-03 19:17:59 25 4
gpt4 key购买 nike

我有一个关于 eslint-plugin-react-hooks 的问题。

我想减少执行 API 调用并将结果存储到状态中的样板代码,因此我创建了一个自定义 Hook :

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;
}

现在自定义钩子(Hook)效果很好,但 eslint-plugin-react-hooks 没有那么多。
我的代码中的警告不是一个大问题。
我知道我可以通过添加评论来消除此警告:
// eslint-disable-next-line react-hooks/exhaustive-deps

问题是自定义钩子(Hook)参数之一是依赖列表,而 eslint-plugin-react-hooks 不会检测到缺少的依赖项。
如何让 eslint-plugin-react-hooks 正确检测自定义 Hook 的依赖项列表问题?
甚至可以对自定义钩子(Hook)进行这种检测吗?

最佳答案

react-hooks/exhaustive-deps规则允许你检查你的自定义钩子(Hook)。来自 Advanced Configuration选项:

exhaustive-deps can be configured to validate dependencies of customHooks with the additionalHooks option. This option accepts a regex tomatch the names of custom Hooks that have dependencies.

{   
"rules": {
// ...
"react-hooks/exhaustive-deps": ["warn", {
"additionalHooks": "(useMyCustomHook|useMyOtherCustomHook)"
}]
}
}

在您的 .eslintrc文件,在“规则”配置中添加以下条目:
'react-hooks/exhaustive-deps': ['warn', {
'additionalHooks': '(useApi)'
}],

然后你应该能够调用你的钩子(Hook)并看到 linter 警告并使用 Quick Fix 选项。
enter image description here

关于reactjs - 带有依赖列表和 eslint-plugin-react-hooks 的自定义钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60097279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com