[当我尝试运行下面的代码时,出现提示警告React Hook useEffect has a missing dependency: 'userApi'. Either include it or remove the dependency array.(react-hooks/exhaustive-deps)
const userApi = useFetch();
useEffect(() => {
userApi.run("/api/user");
}, []);
但是如果我将userApi添加为依赖项,则会得到一个递归循环。如果我忽略警告,一切都很好。我应该忽略它吗?
这是我的useFetch钩子:
const useFetch = () => {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const auth = useAuth();
const run = async (url, method = "GET", data, options) => {
setError();
setIsLoading(true);
try {
const token = await auth.user.getIdToken();
if (!options)
options = {
method,
headers: {
"Content-Type": "application/json"
}
};
if (!options.headers) options.headers = {};
if (!options.headers["Authorization"])
options.headers["Authorization"] = `Bearer ${token}`;
if (!options.body && data) options.body = JSON.stringify(data);
const response = await fetch(url, options);
console.log(response);
if (!response.ok) throw Error(response.statusText);
const json = await response.json();
setData(json);
} catch (e) {
console.log(e);
setError(e.message);
}
setIsLoading(false);
};
return { data, error, isLoading, run };
};
使用eslint-plugin-react-hooks作为React doc可以解决这个问题:
我们建议将exhaustive-deps规则用作eslint-plugin-react-hooks程序包的一部分。当错误指定依赖项时,它会发出警告,并提出修复建议。