React-Router只有一个孩子

Mar*_*rco 68 javascript reactjs react-router

我一直在收到错误:

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

当使用react-router时.

我似乎无法弄清楚为什么这不起作用,因为它与他们在示例中显示的代码完全相同:https://reacttraining.com/react-router/web/guides/quick-start

这是我的代码:

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'));
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助

QoP*_*QoP 143

你必须Route<div>(或者<Switch>)包裹你的.

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

应该

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

jsfiddle/webpackbin

  • 奇怪.为什么是这样? (24认同)
  • 它显示两个路由,因为它使用`div`,你真的应该使用`switch`代替.这使路线独占https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Switch.md (3认同)
  • [`Router`](https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Router.js#L53)期望`this.props.children`为'null `或者长度等于1 (2认同)

Fei*_*anZ 38

这是API的变化react-router 4.x.建议的方法是将Routes 包装在Switch:https://github.com/ReactTraining/react-router/issues/4131#issuecomment-274171357

引用:

兑换

<Router>
  <Route ...>
  <Route ...>
</Router>
Run Code Online (Sandbox Code Playgroud)

<Router>
  <Switch>
    <Route ...>
    <Route ...>
  </Switch>
</Router>
Run Code Online (Sandbox Code Playgroud)

当然,您需要添加Switch到您的导入:

import { Switch, Router, Route } from 'react-router'
Run Code Online (Sandbox Code Playgroud)

  • @NSCoder确保你在模块顶部使用`4.xx`版本的`react-router`和`require`或`import``Twitch` (4认同)