Redux状态下的复杂对象

时间:2018-02-01 16:11:06

标签: javascript reactjs redux

我的React应用程序应该能够显示带有任意模板的模态对话框。像modals.open(ChildComponent)这样的东西。我如何反映" ChildComponent"部分在Redux州?

出于显而易见的原因,存储类/构造函数本身不是一种选择。

维护{'templateOne': ChildComponent, 'templateTwo': AnotherChild}等类的键映射并存储键也感觉很难看。

2 个答案:

答案 0 :(得分:1)

You might consider storing the Class name only in your store, for example let's say you have a JSON response from a server that tells you which components you need to render in a giving view, the response might be similar to this:

{
  "components": [
    { "component": "MyReactComponent1", "title": "Some other params" },
    { "component": "MyReactComponent2", "title": "Some other params" },
    ...more and more
  ]
}

You will add that configuration to your state. In your codebase you should also have a component called MyReactComponent1, which is basically one of the 100 templates you have. When you need to render any of those component you can do something like this:

// import your component catalog
import allComponents from 'my-awesome-package-with-all-my-templates';

// in the render method get the component you need:
render() {
  const { configFromRedux } = this.props;
  const config= configFromRedux[0]; // Get the first configuration
  const Template = allComponents[config.component];

  return (
     <YourModal>
       <Template {...config} />
     </YourModal>
  );
}

One of the disadvantages of this approach is that you need to make sure the server returns a valid component's name, maybe by adding those validations to your CMS.

答案 1 :(得分:0)

您需要的不是将组件存储在Redux状态,而是存储在高阶组件

你的模态HOC看起来像

const CustomModal  = ({Component}) => {
   return class App extends React.Component {
       //Have Custom logic here
       render() {
          return <div>{/* The rest of Modal Content */}<Component {...this.props} /></div>
       }
   }
}

现在你需要模态,你可以像

一样使用它
const MyModal = CustomModal({Component: ChildComponent});

并将其渲染为<MyModal {...this.props}/>

请查看Higher Order Components(HOCs)上的此文档以获取更多详细信息