Reactjs由api返回的多个组件

问题描述 投票:1回答:1

大家好,新年快乐,

我在React-JS中做了一些简单的应用程序。然而,现在我构建了一个更复杂的应用程序,我只想知道我是否朝着正确的方向前进。我没有发现这样的问题所以这里是:

在admin部分,Web编辑器到目前为止可以使用3个不同的模块填充页面。这意味着我的API可以返回如下内容:

{
  "component_name": 'x',
  "title": "Hello world",
  "body": "Nice to see you"
},
{
  "component_name": 'y',
  "image": "http://localhost/image.png",
  "title": "my fancy image"
},
{
  "component_name": 'z',
  "whatever": "test",
  "someting": "test"
}

或类似的东西

{
  "component_name": 'x',
  "title": "Hello world",
  "body": "Nice to see you"
},
{
  "component_name": 'x',
  "title": "Hello again",
  "body": "Nice to see you again"
},
{
  "component_name": 'y',
  "image": "http://localhost/image.png",
  "title": "my fancy image"
}

由于我不知道将返回哪些组件,因此我编写了一个switch语句。正如我之前所说,我没有发现这样的问题,我只想知道这是否正确?或者我在这里从根本上遗漏了什么?

const { components } = this.state;
let xComponent = null;
components.map((item, index) => {

        switch (item.component_name) {
            case 'x':
                xComponent = <xComponent title={item.title} text={item.text} />
                break;
            default:

        }
    });
    return(
        xComponent
    )
javascript reactjs
1个回答
1
投票

我明白你在说什么。您希望基于管理内容管理器构建页面组件。我以前走过那条路,但效果很好。如果您的api返回数据,您可以按照您的描述进行渲染。我在下面写了一个更具体的例子。

class Page extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pageComponents: [{
        "type": 'wysiwyg',
        "props": {
          "title": "Hello world",
          "body": "Nice to see you",
        },
      }, {
        "type": 'video',
        "props": {
          "title": "Hello again",
          "body": "Nice to see you again",
        },
      }, {
        "type": 'image',
        "props": {
          "image": "http://localhost/image.png",
          "title": "my fancy image",
        },
      }],
    };
  }

  render() {
    return this.state.pageComponents.map((item, i) => {
      switch (item.type) {
        case 'wysiwyg':
          return <Wysiwyg key={i} {...item.props} />
          break;
        case 'video':
          return <Video key={i} {...item.props} />
          break;
        case 'image':
          return <Image key={i} {...item.props} />
          break;
        default:
          return null;
      }
    });
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.