我正在为现场讨论创建面板,其中在useEffect中使用了susbcribeToMore。与这里所说的一样,我也使用了在chaat组件中正常工作的逻辑。这是我的代码:
useEffect(() => {
const unsubscribe = subscribeToMore({
document: DISCUSSION_SUBSCRIPTION,
variables: { authUserId: props.userId, groupId: props.groupId },
updateQuery: (prev, { subscriptionData }) => {
if (!subscriptionData) return prev;
const newDiscussion = subscriptionData.data.DiscussionCreated;
console.log(newDiscussion);
console.log(prev);
const mergedDiscussion = [...prev.getDiscussions, newDiscussion];
console.log(mergedDiscussion);
return { getDiscussions: mergedDiscussion };
},
});
return () => {
unsubscribe();
};
}, [props.groupId, props.userId, subscribeToMore]);
发件人X向发件人Y发送讨论消息时,发件人X可以看到他的UI更新了新消息。在发件人Y的控制台中,由于控制台日志,我能够看到newDiscussion和prev,但发件人Y的UI不会更新。但是,仅对于第一个消息,这是正确的。当发件人X发送另一条消息时,控制台日志“ prev”显示为未定义。而且我也收到此错误:
TypeError: Cannot read property 'getDiscussions' of undefined
at updateQuery (NewDiscussionPanel.js:126)
at bundle.esm.js:337
at bundle.esm.js:409
at tryFunctionOrLogError (bundle.esm.js:931)
at ObservableQuery.updateQuery (bundle.esm.js:408)
at Object.next (bundle.esm.js:335)
at notifySubscription (Observable.js:151)
at onNotify (Observable.js:195)
at SubscriptionObserver.next (Observable.js:247)
at Object.next (Observable.js:337)
at notifySubscription (Observable.js:151)
at onNotify (Observable.js:195)
at SubscriptionObserver.next (Observable.js:247)
at bundle.esm.js:1086
at Set.forEach (<anonymous>)
at Object.next (bundle.esm.js:1085)
at notifySubscription (Observable.js:151)
at onNotify (Observable.js:195)
at SubscriptionObserver.next (Observable.js:247)
at Object.next (bundle.esm.js:32)
at notifySubscription (Observable.js:151)
at onNotify (Observable.js:195)
at SubscriptionObserver.next (Observable.js:247)
at Object.handler (client.js:298)
at SubscriptionClient.processReceivedData (client.js:755)
at WebSocket.client.onmessage (client.js:701)```
因此,很明显,用户Y的UI在第二条消息之后仍然没有更新。它仍然为用户X更新。后端已经过测试,并且工作正常,因此这绝对是前端上的错误。如果有人可以帮助我,那将是很棒的。预先感谢!
编辑1:用户X看到消息的原因很可能是因为他们向消息发送UI更新后会导致重新呈现。如果刷新页面,则两个用户都可以看到所有消息。
答案 0 :(得分:0)
我认为您应该使用Object.assign({}, prev, { getDiscussions: mergedDiscussion })
而不是{ getDiscussions: mergedDiscussion }
。