gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:04:47 25 4
gpt4 key购买 nike

我昨天刚开始使用 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;
当我在某处读到 Markikson 提到导入商店但在 thunk 中使用 getState 不是一个好习惯时,我环顾四周并在 documentations 中看到。与 thunk 不同,onStart 中存在用于查询的 getState,您可以从它的第二个参数访问它。
有没有人对此有 onStart 实现?或者进口商店是否可以接受?

最佳答案

通常,我们希望防止人们这样做,这就是为什么您没有 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 在组件中选择该值。并将其作为参数传递到您的查询钩子(Hook)中,而不是将其从 query 中的商店中拉出功能。

关于reactjs - RTK 查询使用 getState() 从另一个切片获取状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67855976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com