我有一个用提供程序包装的应用程序。
在应用程序的更深处,我使用的组件通常是独立的并且有自己的提供程序。
当“Master”商店更新时,我想将信息传递给内部商店。
当我这样做时,我收到了 mobx 的警告:
Mobx Provider: Provider store 'internalStore' has changed. Please avoid replacing stores as the change might not propagate to all children
.
我可以想到两种解决方案 - 1. 将 store (internalStore) 存储在 RootStore 中(双关语) 2.在internalStore中添加更新方法
应用程序
const App = (props) => {
return (
<Provider store={store}>
App...
</Provider>
)
}
内部组件 -
const Internal = (props) => {
return (
<Provider store={internalStore}>
<ReusedCompoenent />
</Provider>
)
}
你觉得怎么样?有想法吗?
最佳答案
这是不可能的。
将内部存储视为某个被引用的松散存储。该商店中的 Prop 是可观察的,并且每个可观察的都会在全局范围内进行跟踪。因此,每次添加商店时,都会有更多可观察到的商店在全局范围内被跟踪。这本身只是一个内存问题。渲染问题是这个新的 Store 的可观察量没有链接到已经存在的 React 组件。因此现有的 react 组件不会触发重新渲染。您必须强制删除并重新创建所有这些组件才能摆脱所有错误的监听器。
但是,如果您想在组件中使用 mobx 状态,我建议您使用以下方法:https://alexhisen.gitbooks.io/mobx-recipes/content/use-observables-instead-of-state-in-react-components.html
除此之外,请尝试使所有商店保持单例。也许这已经解决了您的问题(只要商店没有重新创建,例如:通过 HMR 或类似的东西,您应该没问题)。
关于reactjs - 如何更新 MobX 中的嵌套存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50208589/