首页 > 解决方案 > 如何使用 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”无效。再次按下“获取皮卡丘”按钮时,我应该会看到加载状态。但它的行为就像缓存仍然有效。如何解决这个问题?

标签: reactjsreact-query

解决方案


来自 react-query docs- query invalidation

当使用 使查询无效时invalidateQueries,会发生两件事:

  • 它被标记为stale
  • 如果查询当前正在通过useQuery或相关的钩子呈现,它也将在后台重新获取。

同样在重要的默认值部分:

  • 当有新活动时(查询实例已安装、窗口重新聚焦、网络重新连接......),会在后台自动重新获取陈旧的查询

回顾一下,当您调用 时invalidateQueries(),它会使所有匹配的查询过时,并且在交互时会在后台再次获取过时的查询。如果要显示加载状态,可以根据场景参考 2 种状态:

  • isLoadingtrue第一次获取时或查询缓存被垃圾收集(无缓存)后返回。
  • isFetchingtrue在后台重新获取时返回。当有陈旧的缓存显示为占位符时发生。
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
);

推荐阅读