RTK 查询“use*Query”正在使用缓存的 isLoading 和数据,即使对于不同的参数也是如此

RTK query `use*Query` is using cached isLoading and data even for different args

我是 RTK 查询的新手,我在跨具有不同参数的查询共享数据时遇到问题。

// api.js
const { useGetStuffQuery } = api.injectEndpoints({
  endpoints: (builder) => ({
    getStuff: builder.query({
      query: (stuffId) => ({ url: `http://some.random-url.com/${stuffId}` }),
    }),
  }),
});

// component.js
function(props) {
  const [id, setId] = useState(1);
  const { data, isLoading } = useGetStuffQuery(id);

  if (val === '2') {
    console.log('datttt', data); // this initially prints data from id:1
  }

  return <div>
      <input value={id} onChange={(e) => setId(e.target.value)} />
      {
        isLoading ? <span>loading...</span>
                  : <span>data is: {data}</span>
      }

  </div>
}

当我将 id 从 1 更改为 2 后,我期待看到加载指示器出现。

但是,rtkQuery 似乎仍在使用我之前 useGetStuffQuery(1) 调用的缓存数据,因此我暂时看到了 id1 的数据。一旦对 id2 的请求得到解决——它会更新并重新呈现我的组件。

这种缓存行为是故意的和预期的吗?还是我遗漏了什么?

这是故意的,isLoadingisFetching 的行为不同(isLoading 直到有数据,isFetching 而任何请求是 运行),为了方便,挂钩将始终为您提供已知的最新数据,这样您的 UI 跳动就会减少。

这是explained in the "Query Loading State" docs section:

isLoading refers to a query being in flight for the first time for the given endpoint + query param combination. No data will be available at this time.

isFetching refers to a query being in flight for the given endpoint + query param combination, but not necessarily for the first time. Data may be available from an earlier request at this time.