【发布时间】:2020-08-22 07:18:18
【问题描述】:
目前,我有一个用 javascript 编写的自定义获取数据钩子,它可以工作
import {useState, useEffect} from 'react';
const useApi = apiName => id => {
const [response, setResponse] = useState();
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
const fetching = async () => {
setLoading(true);
const data = await fetch(`/api/${apiName}${id ? `/${id}` : ""}`)
.then((x) => x.json())
.catch((error) => setError(error));
setResponse(data);
setLoading(false);
};
useEffect(() => {
fetching();
}, [id]);
return { response, loading, error };
};
然后我可以使用传递我想调用的 api 来获取钩子。例如:
const useCustomer = useApi("customer")
const useHello = useApi("hello")
.....
const {response, loading, error} = useCustomer("id_1")
效果很好。
然后,我尝试转换为打字稿
const useApi = (apiName:string) => (id?:string) => {
const [response, setResponse] = useState({})
.......
}
而 eslint 抱怨说
React Hook "useState" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function
我想知道这种方法有什么问题,我知道我可以有类似的东西:
const useApi = (apiName:string, id?:string) => {}
或禁用 eslint(react-hooks/rules-of-hooks)
但只是好奇钩子的高阶函数的潜在问题是什么,因为它实际上返回了响应。
谢谢
【问题讨论】:
-
我的猜测是 ESLint 规则无法识别它只是柯里化,它认为这是一个无效的钩子使用。
标签: javascript reactjs typescript react-hooks eslint