如何使用 React query v3 使缓存失效?

Don*_*al0 7 reactjs 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>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

因此该函数getGengar()应该使查询“get-pokemon”无效。再次按下“获取皮卡丘”按钮时,我应该看到加载状态。但它的行为就像缓存仍然有效。如何解决这个问题?

Nea*_*arl 8

来自react-query docs -查询失效

当使用 使查询无效时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
);
Run Code Online (Sandbox Code Playgroud)