首页 > 解决方案 > 在对话框中嵌套的连接组件中找不到“存储”错误

问题描述

我有一个连接的组件,当用 a 包装时可以很好地呈现<div>,但是当我用 Dialog 组件包装时,我一直在担心:在“Connect(MyComponent)”的上下文中找不到“store”。是的,根<App />被包裹<Provider />并且存储很好,所有其他页面、组件、连接的项目都可以访问存储,只是在此对话框中呈现时没有。

这在过去不是问题,并且显然是由于一些正在发生的依赖关系维护而造成的副作用。如果我将 Dialog 组件的底层库从 MUI 0.20 交换到版本 3(通过@material-ui/core/Dialog),它可以正常工作。在 mui 0.20 和更新的 react-ish 依赖项之间取得了平衡。

只是想知道是否有人经历过这种情况?

// Where it's invoked...

<ParentPageComp>
  <Dialog open>
    <MyConnectedComponent />
  </Dialog>
</ParentPageComp>

// What is being attempted to render...

class MyConnectedComponent extends React.Component {
  render() {
    return <div>Yeppers</div>;
  }
 }

export default connect(state => ({ blah: state.blah }))(MyConnectedComponent);

同样,如果我替换<Dialog><div>,一切正常。

不确定这是否相关,但是包装 Dialog 的父组件是用钩子异步加载的……即使用 react-loadable 的代码拆分机制替换,我也会得到相同的顽皮结果。

使用:

标签: reduxreact-reduxdialogmaterial-uistore

解决方案


旧版本可以通过 DOM 层次结构轻松阻止上下文传播。<Dialog/>您可以像这样在组件上手动携带上下文

import { Provider, ReactReduxContext } from 'react-redux';

//...
render() {
    return (
        <ParentPageComp>
            <ReactReduxContext.Consumer>
                {((ctx) => (
                    <Dialog open>
                        <Provider store={ctx.store}>  /* make store available again */
                            <MyConnectedComponent />
                        </Provider>
                    </Dialog>
                )).bind(this) // Dont forget to bind this
                }
            </ReactReduxContext.Consumer>
        </ParentPageComp>
    );
}

推荐阅读