[英]How to fix this “React Hook useEffect has a missing dependency” warning?
Here's my file:这是我的文件:
// 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];
}
On line 21, eslint complaints that:在第 21 行,eslint 抱怨:
React Hook useEffect has a missing dependency: 'loadData'. Either include it or remove the dependency array.eslint(react-hooks/exhaustive-deps)
How can I fix this?我怎样才能解决这个问题?
The best way here would be to define your async function inside the useEffect
:这里最好的方法是在 useEffect 中定义你的异步
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];
}
Add the loadData
function to the array in your useEffect
.将
loadData
function 添加到useEffect
中的数组中。 This will get rid of the complaint:这将摆脱投诉:
useEffect(() => {
loadData();
}, [action, loadData]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.