【问题标题】:RTK Query get state from another slice using getState()RTK Query 使用 getState() 从另一个切片获取状态
【发布时间】:2021-08-23 14:44:45
【问题描述】:

我昨天刚开始使用 redux,在阅读了不同的库后,我决定使用 RTK 中的切片路由。

对于我的异步,我决定使用 RTK 查询,而不是使用 createAsyncThunk,但我对从另一个切片访问状态的正确方法有疑问。

slice1 包含一些用户数据,例如:

export const initialState: IUserState = {
   name: 'example',
   id: null,
};

在我的 slice2 中,我有一个想要执行类似 getSomethingByUserId(id) 的函数和我当前的实现:

interface IApiResponse {
  success: true;
  result: IGotSomethingData[];
}

const getsomethingSlice: any = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({
    baseUrl: 'https://someapibase',
  }),
  endpoints(builder) {
    return {
      fetchAccountAssetsById: builder.query<IApiResponse, null>({
        query() {
          console.log('store can be called here', store.getState().user.id);
          return `/apipath?id=${store.getState().user.id}`;
        },
      }),
    };
  },
});

export default getsomethingSlice;
export const { useFetchAccountAssetsByIdQuery } = getsomethingSlice;

当我在某处读到 markerikson 提到导入商店而不是在 thunk 中使用 getState 不是一个好习惯时,我环顾四周并在 documentations 中看到,与 thunk 不同,onStart 中存在用于查询的 getState您可以从它的第二个参数访问它。

有人对此有 onStart 实现吗?或者导入商店是否可以接受?

【问题讨论】:

    标签: reactjs redux redux-thunk redux-toolkit rtk-query


    【解决方案1】:

    通常,我们希望阻止人们这样做,这就是为什么您没有getStore 可用的原因(您在许多其他地方都有)。

    您会看到,RTK-query 使用您在查询中提供的参数来确定缓存键。 由于您没有传入参数,因此结果的缓存键将存储为fetchAccountAssetsById(undefined)

    所以,你提出了第一个请求,state.user.id 是 5 并且发出了该请求。

    现在,您的 state.user.id 更改为 6。但您的组件调用了 useFetchAccountAssetsByIdQuery() 并且已经有一个 fetchAccountAssetsById(undefined) 的缓存条目,因此仍在使用 - 并且没有发出请求。

    如果您的组件改为调用useFetchAccountAssetsByIdQuery(5) 并且它更改为useFetchAccountAssetsByIdQuery(6),RTK-query 可以安全地识别它有一个fetchAccountAssetsById(5) 的缓存条目,但没有fetchAccountAssetsById(6) 的缓存条目,并将发出一个新请求,检索最新信息。

    因此,您应该使用 useSelector 在组件中选择该值并将其作为参数传递到您的查询挂钩中,而不是在您的 query 函数中将其从存储区中拉出。

    【讨论】:

    • 我明白了,onStart 的 getState 呢?
    • onStart 现在是onQueryStarted,请看the current RC docs。通常,在决定应该运行该查询之后,您会产生副作用。所以整个事情在那里没有发挥作用。
    猜你喜欢
    • 2021-02-06
    • 2023-02-09
    • 2022-12-31
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-28
    • 2020-10-08
    相关资源
    最近更新 更多