【发布时间】:2022-01-09 01:21:19
【问题描述】:
store.js
import {useLocalObservable} from "mobx-react-lite";
function chatStore() {
return {
chatmsg: [],
setChatMsg(arr) {
this.chatmsg = arr
},
addChatMsg(msg) {
this.chatmsg.push(msg)
}
}
}
export const useChatStore = () => useLocalObservable(chatStore)
app.js
const App = () => {
const chatMsgStore = useChatStore()
const AppFunctions = {chatMsgStore}
useEffect(() => {
socket.on(activechat.chatid, (bdmsg) => {
chatMsgStore.addChatMsg(bdmsg)
})
return () => {
socket.off(activechat.chatid)
}
}, [activechat, chatMsgStore.chatmsg])
return (
<>
<AppContext.Provider value={AppFunctions}>
.....................
</AppContext.Provider>
</>
)
}
export default App;
fetch.js
async function getChatMessages(url, body, userStore, chatMsgStore) {
........
chatMsgStore.setChatMsg(firstResData)
........
在应用加载时,我添加了一个套接字侦听器,其依赖是 activechat 和 chatMsgStore。
此侦听器是动态的,必须在 deps 更改时更改。
这个监听器的唯一目的是向 store 添加一个 msg 并重新渲染观察者组件
部门:
activechat - 非商店状态
chatMsgStore.chatmsg - 存储状态
为什么 chatMsgStore.addChatMsg(bdmsg) 不影响存储?所以在 App.js 中嵌套很深的组件不会重新渲染。
否则我有一个函数 getChatMessages 我从 App.js 深处的自定义钩子导入它来设置消息。这个函数不是 App.js 的子函数,它没有被 observer chatMsgStore.setChatMsg(firstResData) 包裹!我可以设置消息,以便观察者组件重新渲染
如何使上述代码生效?
【问题讨论】:
-
这里不需要观察者。这里不需要反应。因为我不在 App.js 组件中呈现任何内容,所以我只是使用 addChatMsg(bdmsg) 方法将数据添加到存储中。我不知道是什么问题,但现在上面的代码效果很好。
标签: mobx mobx-react mobx-react-lite