reactjs - 如何使用 React 查询 v3 使缓存无效?
问题描述
我已阅读有关查询失效的 react-query 文档。但是,它似乎对我不起作用。这是代码:
import React from "react";
import ax from "axios";
import { useQueryClient, useQuery } from "react-query";
export default function App() {
const queryClient = useQueryClient();
const [poke, setPoke] = React.useState("pikachu");
const getPokemon = async (id) => {
try {
const pokemon = await ax.get("https://pokeapi.co/api/v2/pokemon/" + id);
return pokemon;
} catch (err) {
throw new Error();
}
};
const { data, isLoading, isError } = useQuery(
["get-pokemon", poke],
() => getPokemon(poke),
{ cacheTime: 100000000 }
);
const getGengar = () => {
ax.get("https://pokeapi.co/api/v2/pokemon/gengar").then((res) => {
queryClient.invalidateQueries("get-pokemon");
});
};
return (
<>
{isLoading && "loading"}
{isError && "error"}
{data && data.data.id}
<button onClick={() => setPoke("pikachu")}>search pikachu</button>
<button onClick={() => setPoke("ditto")}>search ditto</button>
<button onClick={() => getGengar()}>search gengar</button>
</>
);
}
所以该函数getGengar()
应该使查询“get-pokemon”无效。再次按下“获取皮卡丘”按钮时,我应该会看到加载状态。但它的行为就像缓存仍然有效。如何解决这个问题?
解决方案
来自 react-query docs- query invalidation。
当使用 使查询无效时
invalidateQueries
,会发生两件事:
- 它被标记为stale。
- 如果查询当前正在通过
useQuery
或相关的钩子呈现,它也将在后台重新获取。
同样在重要的默认值部分:
- 当有新活动时(查询实例已安装、窗口重新聚焦、网络重新连接......),会在后台自动重新获取陈旧的查询
回顾一下,当您调用 时invalidateQueries()
,它会使所有匹配的查询过时,并且在交互时会在后台再次获取过时的查询。如果要显示加载状态,可以根据场景参考 2 种状态:
isLoading
:true
第一次获取时或查询缓存被垃圾收集(无缓存)后返回。isFetching
:true
在后台重新获取时返回。当有陈旧的缓存显示为占位符时发生。
const {
isFetching, // returns true when in the fetching process
isLoading, // returns true when in the fetching process AND no cache
...props,
} = useQuery(
["id", idQuery],
fetchSomething
);
推荐阅读
- android - 将动画翻译到Android屏幕的中心
- kubernetes - 使用 Rancher 管道将 docker 镜像推送到私有存储库
- apache-poi - 阿帕奇 POI 4.1。XSSF 合并单元格边框
- c# - 在 Windows 上运行但不在 Linux 上运行的 Dot Net Core 便携式应用程序
- firebase - 如何在 Flutter 中为 Firebase 连接设置监听器?
- sql-server - 使用标量函数的 SQL Server 查询在 FireDAC 上非常慢,并且仅在 FireDAC 上
- mysql - 将不同表中的值相乘
- python - python django在后端获取html标签ID
- swift - 如何使视图与其内容一样高
- android - 超过 1 +1/2 个月我的应用没有投放广告,出现错误 I/Ads: Ad failed to load : 3