我只能考虑在全局某处存储对 updateCachedData 的引用并在该单击事件中使用它,但我不确定这是 React 执行此操作的方式。
我有一个使用 Socket.IO 服务器构建的通知源。
通过单击通知,它应该会从列表中删除。(该列表应仅显示未读通知。)
但是从列表中删除时,我会在通知窗格中创建一个新数组作为状态。
当我收到新通知时,所有已删除的通知都会返回 - 这不是我想要的。
如何更改缓存条目,更准确地从中删除项目,而无需重新请求所有通知?
没有错误消息。
代码
getNotifications: build.query<
IDbNotification[],
IGetNotificationsQueryParams
>({
query: (params: IGetNotificationsQueryParams) => ({
url: `notifications?authToken=${params.authToken || ""}&limit=${
params.limit
}&userId=${params.userId || ""}${
params.justUnread ? "&justUnread" : ""
}`,
method: "GET"
}),
keepUnusedDataFor: 0,
async onCacheEntryAdded(
arg,
{ updateCachedData, cacheDataLoaded, cacheEntryRemoved }
) {
const { myIo, connectHandler } = getWebSocketConnection(
"notifications",
clone({
subscribtions: arg.userId
? getFollowedUserIds().concat({
uid: arg.userId,
justUnread: arg.justUnread
})
: getFollowedUserIds()
})
);
const listener = (eventData: IDbNotification) => {
if (
(eventData as any).subscriber === arg.userId &&
(!arg.justUnread || typeof eventData.readDateTime === "undefined")
) {
updateCachedData(draft => {
draft.unshift(eventData);
if (draft.length > arg.limit) {
draft.pop();
}
});
}
};
try {
await cacheDataLoaded;
myIo.on("notifications", listener);
} catch {}
await cacheEntryRemoved;
myIo.off("notifications", listener);
myIo.off("connect", connectHandler);
}
})