我正在将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”的依赖项警告消息。
答案 0 :(得分:1)
我使用“ useRef” react挂钩,现在缺少依赖项警告已消失。 那是正确的使用吗?
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")**
}
}, []);
}
答案 1 :(得分:0)
缺少依赖项警告是为了通知用户以避免意外的关闭问题。
如果您完全确定所写内容正确无误,则可以禁用该警告
或
您可以通过将函数转换为useCallback,然后将其添加为依赖项来避免警告。请注意,该函数还使用关闭时提供的历史记录,因此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?