reactjs - React Hooks Exhaustive-deps 异步无限循环
问题描述
我有以下组件:
import React, { useState, useEffect } from "react";
const App = () => {
const [data, setData] = useState<null | any[]>(null);
const [checked, setChecked] = useState(false);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
(async () => {
if (data) {
// Could do something else here if data already exsisted
console.log("Data exists already");
}
const ret = await fetch("https://jsonplaceholder.typicode.com/users?delay=1000", { cache: "no-store" });
const json = await ret.json();
setData(json);
setLoading(false);
})();
}, [checked]);
return (
<>
<h1>useEffect Testing {loading && " ⌛"}</h1>
<hr />
<input type="checkbox" checked={checked} onChange={(e) => setChecked(e.target.checked)} />
<pre style={{ fontSize: "0.8em" }}>{JSON.stringify(data)}</pre>
</>
);
};
export default App;
目前,我if(data)
是毫无意义的,但是如果我想检查当前data
状态,然后根据状态运行异步函数,eslint(react-hooks/exhaustive-deps)告诉我钩子缺少data
依赖项,它就是。当我将数据添加到导致无限循环的依赖项列表时,问题就出现了。
知道如何解决这个问题吗?感觉它应该是相当简单的模式,但是我发现的所有内容都建议使用扩展setState(prev => prev + 1)
重载,在这种情况下对我没有帮助。
解决方案
您正在设置data
并在效果中读取它。除非您手动停止它,否则这将导致您陷入无限循环。这里有一些解决方案。
如果有数据则返回而不是修改它:
useEffect(() => {
setLoading(true);
(async () => {
if (data) {
// Could do something else here if data already exsisted
console.log("Data exists already");
return;
}
const ret = await fetch("https://jsonplaceholder.typicode.com/users?delay=1000", { cache: "no-store" });
const json = await ret.json();
setData(json);
setLoading(false);
})();
}, [checked, data]);
消除对设置它的效果的依赖data
(我会做什么):
useEffect(() => {
setLoading(true);
(async () => {
const ret = await fetch("https://jsonplaceholder.typicode.com/users?delay=1000", { cache: "no-store" });
const json = await ret.json();
setData(json);
setLoading(false);
})();
}, [checked]);
useEffect(() => {
if (data) {
// Could do something else here if data already exsisted
console.log("Data changed and exists!");
}
}, [data]);
或者您可以手动执行一些停止无限循环的操作。
useEffect(() => {
if (loading || data) {
console.log('Do something with loading or data, but do not modify it!')
return;
}
setLoading(true);
(async () => {
const ret = await fetch("https://jsonplaceholder.typicode.com/users?delay=1000", { cache: "no-store" });
const json = await ret.json();
setData(json);
setLoading(false);
})();
}, [checked, data]);
推荐阅读
- file - 在 svelte 中显示文件内容
- angular - 如何在星云中没有全局微调器的情况下导航?
- python - 在 Python 中处理执行的系统命令错误
- c# - C# - “非空”条件的级联
- javascript - 如何在 React 中创建新行?
- python - 在 ElasticSearch 中,如何搜索大量关键字
- java - 将 java 从 MainActivity.java 移动到 HomeFragment.java 导致错误认为相同的代码
- c++ - 为散列函数定义一个 c++20 概念
- regex - Nginx 正则表达式
- javascript - Firebase 函数和 API 密钥