[英]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.