Reactjs React:将上下文传递给动态加载的组件
我有一个动态加载的组件,如下所示:Reactjs React:将上下文传递给动态加载的组件,reactjs,react-context,Reactjs,React Context,我有一个动态加载的组件,如下所示: LoadScript("path/to/component.bundle.js", () => { let comp = getComp() ReactDOM.render(<Provider store={store}> {comp} </Provider>, container) }) 但是,MyComponent无法访问存储区(如果未动态加载,则可以工作)。如果我将其更改为:
LoadScript("path/to/component.bundle.js", () => {
let comp = getComp()
ReactDOM.render(<Provider store={store}>
{comp}
</Provider>, container)
})
但是,MyComponent
无法访问存储区(如果未动态加载,则可以工作)。如果我将其更改为:
export function getComp() {
return <Provider store={store}><MyComponent /></Provider>
}
然后,我尝试从“admin”加载“kiosk”包。这就创造了两个商店。这是有意义的,因为两个包索引文件的顶部都有以下内容:
import store from './store'
而store.js
定义为:
...
export default createStore(reducer, middleware)
减速器没有问题,因为它们都包含在两个捆绑包中。
请注意,这不是SPA,而是一个在React中包含一些组件的遗留应用程序。您可以导出一个函数,该函数创建存储(如果不存在),或者返回一个已经存在的实例,而不是导出
createStore
方法
差不多-
let instance;
export default getStore = () => {
if(instance) {
return instance;
} else {
instance = createStore(reducer, middleware);
return instance;
}
}
// might need to improve this to eliminate race conditions,
// or explicitly create the store in this module,
// and only allow getting an already created store.
您还可以检查捆绑包本身是否都有redux
的副本。[我不确定多个入口点如何处理这一点]
今天我遇到了一个问题,动态加载的模块无法访问显然是组件祖先的提供程序。问题在于,动态添加的模块有自己的库副本,而不是使用宿主应用程序的版本。您可以导出一个函数,该函数要么创建不存在的存储,要么返回已经存在的实例,而不是导出
createStore
方法
差不多-
let instance;
export default getStore = () => {
if(instance) {
return instance;
} else {
instance = createStore(reducer, middleware);
return instance;
}
}
// might need to improve this to eliminate race conditions,
// or explicitly create the store in this module,
// and only allow getting an already created store.
您还可以检查捆绑包本身是否都有redux
的副本。[我不确定多个入口点如何处理这一点]
今天我遇到了一个问题,动态加载的模块无法访问显然是组件祖先的提供程序。问题是动态添加的模块有自己的库副本,而不是使用主机应用程序的版本。自2019年以来,也许你应该试试:PRedux仍然是你能找到的更好的工具之一,因为社区非常大,有很多模块。@Kornflex,尝试一下undux,你就会改变主意:P@deano我查一下,谢谢。我还没反应过来。我仍然需要用redux解决这个问题:-)你不能在
getComp()
中执行返回连接(MapStateTrops,mapDispatchToProps)(MyComponent)
?从2019年开始,也许你应该试试:PRedux仍然是你能找到的更好的工具之一,因为社区非常大,有很多模块。@kornflex,尝试一下undux,你就会改变主意:P@deano我查一下,谢谢。我还没反应过来。我仍然需要用redux解决这个问题:-)您不能在getComp()中执行返回连接(MapStateTops,mapDispatchToProps)(MyComponent)
?
let instance;
export default getStore = () => {
if(instance) {
return instance;
} else {
instance = createStore(reducer, middleware);
return instance;
}
}
// might need to improve this to eliminate race conditions,
// or explicitly create the store in this module,
// and only allow getting an already created store.