在reducer redux工具箱中存储mqtt客户端时检测到不可序列化的值



我正试图将MQTT客户端存储在@redux toolkit reducer中,但收到错误"检测到不可序列化的值"那么,有没有比将客户端存储在reducer中更好的方法呢?因为我需要onCacheEntryAddd中的MQTT客户端来更新我的缓存

const client = MQTT(socketUrl, options)
client.stream.on("error", (err) => {
toast.error(`Connection to ${socketUrl} failed`)
client.end()
return
})
dispatch(updateClient(client))

这是我的onCacheEntryAdded函数

async onCacheEntryAdded(
arg,
{ updateCachedData, cacheDataLoaded, cacheEntryRemoved, getState }
) {
try {
const state = getState()
const client = state.inbox.client
await cacheDataLoaded
client.on("message", (topic, data) => {
const message = JSON.parse(data.toString())
updateCachedData((draft) => {
if (!message.payload) return
draft.messages.unshift(message.payload)
})
})
} catch (err) {}
await cacheEntryRemoved
},

Redux的最佳实践是,您的状态不应包含任何不可序列化的值,只应包含原始数据,因此不建议将客户端存储在您的状态中。

我对MQTT不太熟悉,所以我不能保证它会起作用。似乎可以将socketUrloptions变量存储在Redux状态中。然后在onCacheEntryAdded回调内部构造MQTT实例。

async onCacheEntryAdded(
arg,
{ updateCachedData, cacheDataLoaded, cacheEntryRemoved, getState }
) {
try {
const state = getState()
const { socketUrl, options } = state.inbox.clientConfig
const client = MQTT(socketUrl, options)

await cacheDataLoaded
client.on("message", (topic, data) => {
const message = JSON.parse(data.toString())
updateCachedData((draft) => {
if (!message.payload) return
draft.messages.unshift(message.payload)
})
})
} catch (err) {}
await cacheEntryRemoved
client.end()
},

这与文档中的WebSocket流更新示例类似,后者在onCacheEntryAdded内部调用const ws = new WebSocket('ws://localhost:8080')

最新更新