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

卡利姆斯

我有一个名为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或任何其他页面,具体取决于在页面组件中作为“ id”传递给URL参数的内容。

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;

我该如何实现?我不知道。

有其他替代方法吗?

约翰尼·彼得

这样的事情应该工作

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;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将本地文件中的json数据加载到React JS中

如何将Markdown文件加载到React组件中?

(React Native)将本地HTML文件加载到WebView中

在React 0.12中动态渲染React组件

动态加载React组件

将所有图片预加载到create-react-app中

在React中动态创建组件

动态将反应图标加载到组件中

将异步数据加载到React组件中

动态将组件加载到动态位置

滑行图像未加载到React Native本机UI组件中

动态导入和延迟加载React组件

如何将动态数据加载到react-native-chart-kit?

显示react-placeholder骨架,直到图像完全加载到页面中

如何使用import()在React中动态加载组件?

如何通过在React中的兄弟组件上单击事件将图像加载到另一个组件中

将jQuery加载到React应用的Mocha测试中

带有JSX的React:将JSX中定义的类加载到HTML中

将javascript标签加载到React组件中

将XHR数据加载到React Redux路由页面中时,事件的顺序是什么?

如何将简单的 React NPM 组件加载到应用程序中

React Loadable 在动态加载的组件中请求新的 css

在 Webpack 4 中,我们是否可以使用 import() 令牌动态生成页面块,以便我们可以将 React 组件转换为可加载的 React 组件?

如何在 React Routers 中嵌套动态页面路由组件?

如何在将数据加载到 UseEffect 中的数组后执行排序 - React Native

如何将 firebase 数据异步加载到 react-redux 中?

在 React 中重新加载页面将导致没有 props

动态内容未加载到扩展组件的 React 类中

React native - 在页面加载时从 JSON 动态添加组件