React-Router只有一个孩子

我继续得到错误:

“路由器”可能只有一个子元素

当使用react-router时。

我似乎无法弄清楚为什么它不起作用,因为它与示例中显示的代码完全一样:快速入门

这是我的代码:

import React from 'react';
import Editorstore from './Editorstore';
import App from './components/editor/App';
import BaseLayer from './components/baselayer';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import {render} from 'react-dom';

const root = document.createElement('div');
root.id = 'app';
document.body.appendChild(root);

const store = new Editorstore();
const stylelist = ['https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.2/semantic.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css', 'https://api.tiles.mapbox.com/mapbox-gl-js/v0.33.1/mapbox-gl.css'];

stylelist.map((link) => {
    const a = document.createElement('link');
    a.rel = 'stylesheet';
    a.href = link;
    document.body.appendChild(a);
    return null;
});

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

感谢您的帮助

猿飞云2020/03/17 12:06:07

出现此问题时,你没有父标签之前<Route>里面<Router>这样来解决这一问题保持<Route>封闭在一个父标签如<div><p>等为例-

<Router>
    <p>
       <Route path="/login" component={Login} />
       <Route path="/register" component={Register} />
    </p>
</Router>
JimLEYSam2020/03/17 12:06:06

如果要在路由器内部嵌套其他组件,则应该这样做。

  <Router>
     <div>
       <otherComponent/>
         <div>
           <Route/>  
           <Route/>
           <Route/>
           <Route/>
         </div>
      </div>
    </Router>
西门村村古一2020/03/17 12:06:06

您还可以将所有路线包裹在默认为索引页面的父路线中

<Router history={history}>    
   <Route path="/" component={IndexPage}>
      <Route path="to/page" component={MyPage}/>
      <Route path="to/page/:pathParam" component={MyPage}/>
   </Route>    
</Router>