reactjs - React Hooks useCallback 依赖无限循环
问题描述
我目前在组件安装时获取我的数据一次,然后在用户单击按钮时获取。但是,如果请求正在进行中,我想停止获取按钮,这就是我更新isFetching
状态的原因。
但是,我需要将 添加isFetching
到useCallback
依赖项以删除警告,如果这样做,则会触发无限获取循环。
这是我的代码:
import { useCallback, useEffect, useRef, useState } from 'react';
export const MyComponent = () => {
const isMounted = useRef(true);
const [isFetching, setIsFetching] = useState(false);
const [data, setData] = useState(null);
// Can also be called from the button click
const getMyData = useCallback(() => {
if (isFetching) return;
setIsFetching(true);
fetch('get/my/data')
.then((res) => {
if (isMounted.current) {
setData(res.data);
}
})
.catch((err) => {
if (isMounted.current) {
setData("Error fetching data");
}
})
.finally(() => {
if (isMounted.current) {
setIsFetching(false);
}
});
}, []); // isFetching dependency warning as is, if added then infinite loop
useEffect(() => {
isMounted.current = true;
getMyData();
return () => {
isMounted.current = false;
};
}, [getMyData]);
return (
<div>
<button onClick={getMyData}>Update data</button>
<p>{data}</p>
</div>
);
};
我知道有多个像这样的问题,但我无法删除警告或无限循环,同时仍在检查组件是否已安装。
解决方案
转换isFetching
为 ref,因此它的值不会是函数的依赖项:
const { useCallback, useEffect, useRef, useState } = React;
const MyComponent = () => {
const isMounted = useRef(true);
const isFetching = useRef(false);
const [data, setData] = useState([]);
// Can also be called from the button click
const getMyData = useCallback(() => {
console.log('call');
if (isFetching.current) return;
isFetching.current = true;
fetch('https://cat-fact.herokuapp.com/facts')
.then(res => res.json())
.then(res => {
if (isMounted.current) {
setData(res);
}
})
.catch((err) => {
if (isMounted.current) {
setData("Error fetching data");
}
})
.finally(() => {
if (isMounted.current) {
isFetching.current = false;
}
});
}, []); // isFetching dependency warning as is, if added then infinite loop
useEffect(() => {
isMounted.current = true;
getMyData();
return () => {
isMounted.current = false;
};
}, [getMyData]);
return (
<div>
<button onClick={getMyData}>Update data</button>
<ul>
{
data.map(({ _id, text }) => (
<li key={_id}>{text}</li>
))
}
</ul>
</div>
);
};
ReactDOM.render(
<MyComponent />,
root
);
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>
推荐阅读
- google-apps-script - 在 Google 表格中 - 在一个单元格中创建一个链接来组合来自两个单元格的信息?
- macros - 如何编写类似于 Ecto 的 field/2 的 Elixir 宏?
- sql - 如何从Oracle中给定字符串的前两个单词中获取前两个字符
- python - 如何将系列对象转换为单个字符串
- groovy - 没有索引的 jsonBuilder
- excel - VBA(Excel宏)中的循环限制问题
- excel - 达克斯。根据另一列的最大值获取一列的值
- c# - HttpClient 在 IIS 上的 ASP.NET Core 上返回错误 404,但适用于 IIS Express
- amazon-web-services - 外部用户的 Redshift?
- javascript - 如何使用 Vue.js 删除嵌套的 Firebase 数据