如何解决此 "React Hook useEffect has a missing dependency" 警告?
How to fix this "React Hook useEffect has a missing dependency" warning?
这是我的文件:
// 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 行,eslint 抱怨:
React Hook useEffect has a missing dependency: 'loadData'. Either include it or remove the dependency array.eslint(react-hooks/exhaustive-deps)
我该如何解决这个问题?
将 loadData
函数添加到 useEffect
中的数组。这将消除投诉:
useEffect(() => {
loadData();
}, [action, loadData]);
这里最好的方法是在 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 中的更多信息。
这是我的文件:
// 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 行,eslint 抱怨:
React Hook useEffect has a missing dependency: 'loadData'. Either include it or remove the dependency array.eslint(react-hooks/exhaustive-deps)
我该如何解决这个问题?
将 loadData
函数添加到 useEffect
中的数组。这将消除投诉:
useEffect(() => {
loadData();
}, [action, loadData]);
这里最好的方法是在 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 中的更多信息。