React - Dynamically Import Components

前端 未结 8 1568
别那么骄傲
别那么骄傲 2020-12-05 07:14

I have a page which renders different components based on user input. At the moment, I have hard coded the imports for each component as shown below:

    imp         


        
相关标签:
8条回答
  • 2020-12-05 08:16

    You can use Route and Switch from 'react-router-dom' to dynamically render components based on the path. Here is the sample

    render() {
    return (
      <>
        <Header  />
        <BrowserRouter>
          <Switch>
            <Route path="/abc" exact render={() => (<Abc />)}/>
            <Route path="/abcd" exact render={() => (<Abcd {...this.props} />)}/>
            <Route path="/xyz" exact render={() => (<Xyz />)}/>
            
          </Switch>
        </BrowserRouter>
        <Footer /></>
    );  }
    
    0 讨论(0)
  • 2020-12-05 08:19

    Since the question is really old, the answers maybe were ok. But nowadays, if someone have the same problem should use dynamic import, in order to load only the component needed and avoid to load all the different ones.

    const component = React.lazy(() => import('./component.jsx'));
    

    try the example here: demo

    0 讨论(0)
提交回复
热议问题