【问题标题】:why chatMsgStore.addChatMsg(bdmsg) does not effect the store?为什么 chatMsgStore.addChatMsg(bdmsg) 不影响存储?
【发布时间】: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)
........

在应用加载时,我添加了一个套接字侦听器,其依赖是 activechatchatMsgStore
此侦听器是动态的,必须在 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


【解决方案1】:

您的 App 组件未使用 observer HOC 包装,因此它不会对 observable 值的更改做出反应。

这样包装:

const App = observer(() => {
  // ...
})

或在导出时:

export default observer(App)

More info in the docs

【讨论】:

    【解决方案2】:

    您应该使用mobx 中的autorun 来正确设置useEffect 中的反应性,here 是一个文档链接,该文档解释了为什么以及如何使用它。

    但我认为你不应该将 chatMsgStore.chatmsg 放在 deps 数组中,因为你没有在 useEffect 中使用它。

    如果你能提供一个可行的例子,也许我们可以进一步帮助你。

    【讨论】:

      猜你喜欢
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 2014-12-08
      相关资源
      最近更新 更多