我正在从Python的后端和前端迁移到带有REACT前端的Python REST api。为了测试API请求,我正在遵循this教程。现在,使用他们的代码可以工作,并且允许我执行API调用,但是ESLint给出了ESLint: React Hook useEffect has missing dependencies: 'data', 'options.body', 'options.method', and 'options.query'. Either include them or remove the dependency array.
警告。自动修复它仅包含这些变量(尽管奇怪的是,选项已经通过jsonOptions包含在内)。
自动修复会破坏代码-屏幕停留在加载屏幕上,这似乎是由于无限循环而发生的。我见过其他一些用户经历过这种情况的帖子,但这通常是由于功能依赖性所致,我不确定这是否存在于我的问题中。
要使用正确依赖项,我需要做什么?消除ESLint错误的一件事是引入(data, options)
作为useEffect函数的输入。 useEffect的输入和依赖项之间有什么区别?
下面是我当前正在使用的代码,该代码可以正常工作并显示ESLint错误。
export default (url, options = { body: {}, query: {} }) => {
// Initialize fetch data
const [data, setData] = useState({
response: null,
error: false,
loading: true,
});
// Extracting jsonOptions dependency so code can be checked more easily
const jsonOptions = JSON.stringify(options);
useEffect(() => {
// Set the fetch data
setData({ ...data, error: null, loading: true });
// Execute json fetch asynchronously
fetch(createUrl(url, options.query), {
method: options.method || "GET",
headers: {
"Content-Type": "application/json",
},
body: options.method !== "GET" && JSON.stringify(options.body),
})
// As soon as we have a response
.then(async response => {
const data = await response.json();
// Update fetch data
setData({
response: data,
error: !response.ok,
loading: false,
})
})
// If any error is returned
.catch(error => {
//fetch throws an error only on network failure or if anything prevented the request from completing
setData({
response: { status: "network_failure" },
error: true,
loading: false,
})
})
}, [url, jsonOptions]);
//[url, jsonOptions, data, options.query, options.method, options.body]);
// data, options.query, options.method, options.body not originally written, added because of ESlint
return data
}