pubnub removeListener 不会在 useEffect 上触发 return
pubnub removeListener doesn't trigger on useEffect return
虽然打开单个聊天可以完美运行,但进入聊天,然后离开聊天屏幕并再次进入聊天会导致双重消息传递,尽管将监听器放置在 useEffect 中的 return 上,但它并没有被删除
我什至在这个线程中尝试了解决方案:
希望大家能帮我找出问题所在。提前致谢!
useEffect(() => {
const listener = {
message: (envelope: any) => {
if (envelope) {
const message = {
channel: envelope.channel,
message: {
...envelope.message,
},
uuid: envelope.publisher,
timetoken: envelope.timetoken,
}
dispatch(setMessage(message))
// this log activates the same amount of times you entered and left the chat, because the listener isn't being removed
console.log('Message listener activated!')
}
// setLastTimeToken(message.timetoken)
},
}
pubnub.addListener(listener)
pubnub.setUUID(employer._id)
pubnub.fetchMessages(
{
channels: [ch],
count: 100,
},
(status, response) => {
if (response.channels[ch]) {
dispatch(setMessages(response?.channels[ch]))
} else {
dispatch(setMessages([]))
}
},
)
pubnub.subscribe({ channels: [ch] })
const usersInfo = channel.split('_')
if (channel != employer._id && usersInfo[1] !== 'job') {
const deeberId = usersInfo[0]
getCandidateById(deeberId).then(res => {
dispatch(setSelectedChatCandidate(res))
})
}
renderDisplayName()
return () => {
pubnub.removeListener(listener)
pubnub.unsubscribeAll()
}
}, [])
升级 PubNub JS SDK 修复了导致多次回调触发的问题。
https://www.pubnub.com/docs/sdks/javascript/changelog#uv4342u
虽然打开单个聊天可以完美运行,但进入聊天,然后离开聊天屏幕并再次进入聊天会导致双重消息传递,尽管将监听器放置在 useEffect 中的 return 上,但它并没有被删除
我什至在这个线程中尝试了解决方案:
希望大家能帮我找出问题所在。提前致谢!
useEffect(() => {
const listener = {
message: (envelope: any) => {
if (envelope) {
const message = {
channel: envelope.channel,
message: {
...envelope.message,
},
uuid: envelope.publisher,
timetoken: envelope.timetoken,
}
dispatch(setMessage(message))
// this log activates the same amount of times you entered and left the chat, because the listener isn't being removed
console.log('Message listener activated!')
}
// setLastTimeToken(message.timetoken)
},
}
pubnub.addListener(listener)
pubnub.setUUID(employer._id)
pubnub.fetchMessages(
{
channels: [ch],
count: 100,
},
(status, response) => {
if (response.channels[ch]) {
dispatch(setMessages(response?.channels[ch]))
} else {
dispatch(setMessages([]))
}
},
)
pubnub.subscribe({ channels: [ch] })
const usersInfo = channel.split('_')
if (channel != employer._id && usersInfo[1] !== 'job') {
const deeberId = usersInfo[0]
getCandidateById(deeberId).then(res => {
dispatch(setSelectedChatCandidate(res))
})
}
renderDisplayName()
return () => {
pubnub.removeListener(listener)
pubnub.unsubscribeAll()
}
}, [])
升级 PubNub JS SDK 修复了导致多次回调触发的问题。 https://www.pubnub.com/docs/sdks/javascript/changelog#uv4342u