这是我的文件:
// useFetcher.js
import { useEffect, useState } from "react";
export default function useFetcher(action) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [data, setData] = useState(null);
async function loadData() {
try {
setLoading(true);
const actionData = await action();
setData(actionData);
} catch (e) {
setError(e);
} finally {
setLoading(false);
}
}
useEffect(() => {
loadData();
}, [action]);
return [data, loading, error];
}
在第21行,投诉以下内容:
React Hook useEffect has a missing dependency: 'loadData'. Either include it or remove the dependency array.eslint(react-hooks/exhaustive-deps)
我该如何解决?
答案 0 :(得分:1)
最好的方法是在useEffect
内定义异步函数:
export default function useFetcher(action) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [data, setData] = useState(null);
useEffect(() => {
async function loadData() {
try {
setLoading(true);
const actionData = await action();
setData(actionData);
} catch (e) {
setError(e);
} finally {
setLoading(false);
}
}
loadData();
}, [action]);
return [data, loading, error];
}
docs中的更多信息。
答案 1 :(得分:0)
将loadData
函数添加到useEffect
中的数组中。这样可以消除投诉:
useEffect(() => {
loadData();
}, [action, loadData]);