【问题标题】:How to update nested store in MobX如何更新 MobX 中的嵌套存储
【发布时间】:2018-05-08 19:00:12
【问题描述】:

我有一个使用 Provider 包装的应用程序。 在应用程序的更深处,我使用的组件通常是独立的并且有自己的 Provider。 当“主”商店更新时,我想将信息传递给内部商店。 当我这样做时,我收到了来自 mobx 的警告说 - Mobx Provider: Provider store 'internalStore' has changed. Please avoid replacing stores as the change might not propagate to all children.

我可以想到两种解决方案 - 1.将存储(internalStore)存储在RootStore中(双关语) 2.给internalStore添加更新方法

应用

const App = (props) => { return ( <Provider store={store}> App... </Provider> ) }

内部组件-

const Internal = (props) => { return ( <Provider store={internalStore}> <ReusedCompoenent /> </Provider> ) }

你怎么看?想法?

【问题讨论】:

  • 如果您想在rootStore 中的某些内容发生更改时更新您的internalStore,难道您不能将两个商店都放在最顶层的提供程序中并在internalStore 中使用计算值派生自rootStore?中的值?
  • 在 mobx 文档中,有一点关于合并商店可能会对您有所帮助:mobx.js.org/best/store.html#combining-multiple-stores

标签: reactjs mobx


【解决方案1】:

这是不可能的。

将内部存储视为引用的松散存储。这个商店的道具是可观察的,每个可观察的都是全局跟踪的。因此,每次添加商店时,都会在全球范围内跟踪更多可观察的数据。这本身只是一个内存问题。渲染问题是这个新的 Store it's observables 没有链接到已经存在的 react 组件。因此现有的反应组件不会触发重新渲染。您将不得不强制删除并重新创建所有这些组件以摆脱所有错误的侦听器。

但是,如果您想在组件中使用 mobx 状态,我建议您使用以下方法:https://alexhisen.gitbooks.io/mobx-recipes/content/use-observables-instead-of-state-in-react-components.html

除此之外,尽量让您的所有商店保持单身。也许这已经解决了你的问题(只要不重新创建商店,例如:通过 HMR 或类似的东西你应该没问题)。

【讨论】:

    猜你喜欢
    • 2019-01-29
    • 1970-01-01
    • 2015-11-15
    • 2011-10-07
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多