reactjs RTK查询使用getState()从另一个切片获取状态

vbkedwbf  于 4个月前  发布在  React
关注(0)|答案(2)|浏览(77)

我昨天刚开始使用redux,在阅读了不同的库之后,我决定使用RTK的切片路由。
对于我的MySQL,而不是使用MySQL AsyncThunk,我决定使用RTK查询,我有一个问题,从另一个切片访问状态的正确方法。
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提到导入store不是一个好的做法,而是在thunk中使用getState,我看了一下,在documentations中看到有getState用于onStart中存在的查询,不像thunk,你可以从它的第二个参数访问它。
有人有onStart实现吗?或者导入商店可以接受吗?

wwodge7n

wwodge7n1#

一般来说,我们希望防止人们这样做,这就是为什么你没有getStore(你在许多其他地方)。
你看,RTK查询使用你给予到查询中的参数来确定该高速缓存键。因为你没有传入参数,所以该高速缓存键的结果将被存储为fetchAccountAssetsById(undefined)
所以,你发出了第一个请求,state.user.id是5,这个请求被发出了。
现在,您的state.user.id更改为6。但是您的组件调用useFetchAccountAssetsByIdQuery(),并且已经有fetchAccountAssetsById(undefined)的缓存条目,因此仍然在使用-并且没有请求。
如果您的组件将调用useFetchAccountAssetsByIdQuery(5),并且它更改为useFetchAccountAssetsByIdQuery(6),RTK查询可以安全地识别它有fetchAccountAssetsById(5)的缓存条目,但没有fetchAccountAssetsById(6),并将发出新的请求,检索最新信息。
因此,您应该使用useSelector在组件中选择该值,并将其作为参数传递到查询钩子中,而不是将其从query函数的存储中取出。

e1xvtsh3

e1xvtsh32#

你可以从中得到一些想法。这是为了改变basequery的头,根据国家。

const baseQuery = fetchBaseQuery({
  baseUrl: 'https://api.your-really-great-app.com/v1/',
  prepareHeaders: (headers, { getState }) => {
    const token = (getState() as RootState).auth.token;
    // If we have a token set in state, let's assume that we should be passing it.
    if (token) {
      headers.set('authorization', `Bearer ${token}`);
    }
    return headers;
  },
})

字符串

相关问题