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

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

来自反应查询文档 - query invalidation.

When a query is invalidated with invalidateQueries, two things happen:

  • It is marked as stale.
  • If the query is currently being rendered via useQuery or related hooks, it will also be refetched in the background.

也在 important defaults 部分:

  • 过时的查询 会在后台自动重新提取 有新活动(已安装查询实例、window 重新聚焦、重新连接网络...)

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

  • isLoading: returns true 首次获取时或查询缓存被垃圾收集后(无缓存)。
  • isFetching: returns 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
);