React-Router only one child

后端 未结 10 1731
执笔经年
执笔经年 2020-12-07 14:32

I keep on getting the error:

A \'Router\' may have only one child element

when using react-router.

I can\'t seem to fig

相关标签:
10条回答
  • 2020-12-07 15:15

    I am using react-router-dom package with version 5.0.1 and it works perfectly fine with your code.

    import { BrowserRouter as Router , Router, Link } from 'react-router-dom';
    import Home from './pages/Home';
    import About from './pages/About';
    ...
    
    class App extends React.Component {
      render() {
        return (
          <Router>
            <ul>
              <li><Link path='/'>Home</Link></li>
              <li><Link path='/about'>About</Link></li>
            </ul>
            <Route path='/' exact component={Home} />
            <Route path='/about' component={About} />
          </Router>
        );
      }
    }
    
    export default App;
    
    0 讨论(0)
  • 2020-12-07 15:16

    I put all my <Route /> tags inside the <Switch> </Switch> tag like this.

        <BrowserRouter>
            <Switch>
                <Route path='/' component={App} exact={true} /> 
                <Route path='/form-example' component={FormExample} />
            </Switch>
        </BrowserRouter>
    

    This solves the problem.

    0 讨论(0)
  • 2020-12-07 15:22

    You have to wrap your Route's in a <div>(or a <Switch>).

    render((
      <Router>
        <Route exact  path="/" component={BaseLayer} />
        <Route path="/editor" component={App} store={store} />
      </Router>
    ), document.querySelector('#app'));
    

    should be

    render((
      <Router>
        <div>
           <Route exact  path="/" component={BaseLayer} />
           <Route path="/editor" component={App} store={store} />
        </div>
      </Router>
    ), document.querySelector('#app'));
    

    jsfiddle / webpackbin

    0 讨论(0)
  • 2020-12-07 15:25

    you can also wrap all your route in a parent route which defaults to index page

    <Router history={history}>    
       <Route path="/" component={IndexPage}>
          <Route path="to/page" component={MyPage}/>
          <Route path="to/page/:pathParam" component={MyPage}/>
       </Route>    
    </Router>
    
    0 讨论(0)
提交回复
热议问题