![](/img/trans.png)
[英]No eslint warning when ref is missing in useEffect dependency
[英]How to handle eslint missing dependencies warning on useEffect of Reat Hooks
我將 useEffect 用於初始數據
export const ChannelConfig = (id) => {
const history = useHistory();
const dataUrl = "/channel/"+id;
useEffect(() => {
fetch(dataUrl + "/configure")
.then((resp) => {
if (resp.ok) {
return resp.json();
} else {
handleError(resp, "Server");
}
})
.then((data) => {
setSrcValue(data);
setEditValue(data);
})
}, []);
... ...
function handleError(resp, entity) {
resp.json().then((err) => {
customToast.error(resp.status, err, entity);
if (resp.status === 404) {
history.push("/pages/error-404")
}
});
}
我收到了這個警告
React Hook useEffect has missing dependencies: 'dataUrl' and 'handleError'. Either include them or remove the dependency array react-hooks/exhaustive-deps
使用useEffect我錯了嗎?
而且,另外,當我將“function handleError”轉換為“useCallback”時,我收到了來自 eslint 的關於“history”的缺少依賴項警告消息。
我使用“useRef”反應鈎子,現在缺少依賴項警告消失了。 這樣使用合適嗎??
export const ChannelConfig = (id) => {
**const history = useRef(useHistory());**
const dataUrl = "/channel/"+id;
useEffect(() => {
fetch(dataUrl + "/configure")
.then((resp) => {
if (resp.ok) {
return resp.json();
} else {
handleError(resp, "Server");
}
})
.then((data) => {
setSrcValue(data);
setEditValue(data);
})
}, [dataUrl]);
... ...
const handleError = useCallback((resp, entity) => {
resp.json().then((err) => {
customToast.error(resp.status, err, entity);
if (resp.status === 404) {
**history.current.push("/pages/error-404")**
}
}, []);
}
缺少依賴警告是為了通知用戶避免意外關閉問題。
如果您絕對確定您所寫的內容是正確且有意的,則可以禁用該警告
或者
您可以選擇通過將 function 轉換為使用 useCallback 然后將其添加為依賴項來繞過警告。 請注意,function 還使用從關閉時提供給它的歷史記錄,因此 useCallback 也會警告您使用它。
您可以將歷史記錄添加到 useCallback 作為依賴項,因為它不會改變
export const ChannelConfig = (id) => {
const history = useHistory();
const dataUrl = "/channel/"+id;
...
const handleError = useCallback(function(resp, entity) {
resp.json().then((err) => {
customToast.error(resp.status, err, entity);
if (resp.status === 404) {
history.push("/pages/error-404")
}
});
}, [history]);
useEffect(() => {
fetch(dataUrl + "/configure")
.then((resp) => {
if (resp.ok) {
return resp.json();
} else {
handleError(resp, "Server");
}
})
.then((data) => {
setSrcValue(data);
setEditValue(data);
})
}, [handleError]);
... ...
請查看這篇文章以獲取有關此問題的更多詳細信息: How to fix missing dependency warning when using useEffect React Hook?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.