React - 将组件动态加载到页面中

时间:2018-06-18 22:49:38

标签: javascript reactjs react-router url-routing

我有一个名为Item.js的静态组件

Routes.js

export default () => (
  <Provider store={store}>
    <BrowserRouter>
      <Switch>
        <Route path="/posts" component={Posts} />
        <Route path="/form" component={Postform} />
        <Route exact path="/" component={App} />
        <Route path="/items" component={Items} />
        <Route path="/cart" component={Cart} />
        <Route path="/page/:id" component={Page} />
      </Switch>
    </BrowserRouter>
  </Provider>
);

在上面的页面组件中,我想加载item.js或任何其他页面,具体取决于传递给URL的参数是什么&#34; id&#34;在页面组件中。

import React, { Component } from 'react';
import Navbar from './Navbar';
import Item from './pages/Item';

class Page extends Component {
  componentDidMount() {
    const { id } = this.props.match.params;
    console.log(id);
  }

  render() {
    return (
      <div>
        <Navbar />
        <div>Hello</div>
      </div>
    );
  }
}

export default Page;

我如何实现这一目标?我不知道。

有没有其他方法可以做到这一点?

3 个答案:

答案 0 :(得分:1)

这样的事情应该有效

import React from 'react';
import Navbar from './Navbar';
import Item from './pages/Item';

const components = [{
  id: 'your/id/passed/in/param'
  component: Item
}]

class Page extends React.Component {

  state = {
    Component: null,
  }

  componentDidMount() {
    const { id } = this.props.match.params;
    this.setState({ Component: components.find(comp => comp.id === id).component })
  }

  render() {
    const { Component } = this.state;
    return (
      <div>
        <Navbar />
        <Component /> 
      </div>
    );
  }
}

export default Page;

答案 1 :(得分:0)

您可以像这样创建索引文件:

index.js:

import Item from './item';

const pages = {
  pageId: Item,
};

export default pages;

在页面组件中:

import React, { Component } from 'react';
import Navbar from './Navbar';
import Item from './pages/Item';
import pages from './pages';

class Page extends Component {
  componentDidMount() {
    const { id } = this.props.match.params;
    console.log(id);
  }

  render() {
    const { id } = this.props.match.params;
    if (pages[id]) {
      return pages[id];
    }
    return (
      <div>
        <Navbar />
        <div>Hello</div>
      </div>
    );
  }
}
export default Page;

以便根据id动态加载组件。

答案 2 :(得分:0)

好吧,我通过遵循约翰尼·彼得(Johnny Peter)的答案来解决它。

Page.js

import React, { Component } from 'react'
import Navbar from './Navbar';
import components from './indexPage'


  class Page extends Component {

     render() {
    const { id } = this.props.match.params;
    const PageComponent = components.find(comp => comp.id === id).component;

    return (
      <div>
        <Navbar />
        <PageComponent/>
      </div>
    );
  }
}


export default Page;

indexPage.js

import Item from './pages/Item'
import Meow from './pages/Meow'

const components = [{
    id: 'item',
    component: Item
  },
  {
    id: 'meow',
    component: Meow
  }
]

export default components;