我正在使用 MapBox 中的地图,每次 onDragStopped 后,地图的边界都会作为 {nw,ne,se,sw} 坐标发送到服务器,其中这些边界的几何形状与存储的区域几何形状进行比较(县、国家、...)。如果这些区域与地图多边形相交,它们将作为 ID 数组返回(“AF”= 阿富汗)。
目前,我正在使用这种方法进行 RTK 查询(其中 mapPolygon 是从 redux 存储中选择的):
const allRegionsQuery = useGetAllRegionsWithinBoundsQuery(
{ bbox: mapPolygon },
{
skip: mapPolygon === null
}
);
这种方法可行,但由于当用户移动地图时,mapPolygon 本质上总是不同的,RTK 最终会存储多个查询结果,其中参数不同,但新数据可能只添加了一个新区域。
如何获取地图的相交区域,但仅使用新区域更新同一客户端对象,以便本地存储的区域集是以下区域的并集 所有查询结果?这只能通过 RTK 查询来完成吗?还是我必须考虑采用不同的方法?
例如:
localRegions = ['AF', 'BE'];
mostRecentQueryResult = ['AF', 'JP', 'AU'];
---
updatedLocalRegions = ['AF', 'BE', 'JP', 'AU']
我读过或考虑过的方法:
是的,在这种情况下,RTKQ 不会为您提供太多帮助 - 您仍然可以使用它来获取,但必须将存储移至单独的切片中,也许可以通过在自定义切片中使用
extraReducers
与您的端点的已完成匹配器。
为了解决这个用例,我们可以利用 RTK 查询中的手动缓存更新机制。
手动缓存更新机制提供了称为乐观更新和悲观更新的功能。
// below method is defined as part of createApi
getList: builder.query<TPortfolio, void>({
query: () => 'list/cartoon',
extraOptions: {
retryCondition: (error, args, options) => {
if (options.attempt >= 1 && error.status === 500) {
return false;
}
return true;
},
},
async onQueryStarted(_, { dispatch, queryFulfilled }) {
try {
const res = await queryFulfilled;
setTimeout(() => {
dispatch(
portfolioApi.util.updateQueryData('getCartoonList', undefined, () => {
return res?.data;
}),
);
}, 10000);
} catch (e) {
console.error(e);
}
},
}),
所以这里我们尝试从 getList 方法更新 getCartoonList 的缓存数据,并且这两个方法可以有不同的 API 调用。
RTK 查询导出这些用例的 thunk,附加到 api.utils: