一个“ <router>可能只有一个子元素”,这是我得到的错误

时间:2018-09-07 20:52:51

标签: javascript reactjs

由于我是React的新手,所以我尝试将我的App封装在Router中,但是遇到此错误,我将其封装在div中,但仍然无法正常工作,有人可以帮助我吗? 很抱歉,如果这个问题无关或愚蠢。

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import routes from'./routes';
import {Router } from 'react-router-dom';
import history from './history';
import App from './App';

ReactDOM.render(
    <Router history={history} routes={routes} >
       <div>
           <App/>
       </div>
    </Router>, document.getElementById('root')); 

当我使用1条路线时,它起作用,但是当我使用2条路线时,错误不在这里

import React, { Component } from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import AddDetails from './components/AddDetails';
import ShowDetails from'./components/ShowDetails';
import NavBar from "./components/NavBar";

class App extends Component {
    render() {
        return (
            <div >
                <NavBar/>
                <BrowserRouter>

                   <Switch>
                        <Route exact={true} path='/' render={() => (
                            <div>
                                <AddDetails />
                            </div>
                        )}/>
                        <Route exact={true} path='details' render={() => (
                            <div>
                                <ShowDetails />
                            </div>
                        )}/>
                    </Switch>
               </BrowserRouter>

           </div>
        );
    }
}

export default App;

3 个答案:

答案 0 :(得分:2)

这应该有效:

Home

根据您的更新,您应该用div包裹路由器,也可以使用switch:

ReactDOM.render((
  <Router history={history} routes={routes} >
     <App/>
  </Router>),
  document.getElementById('root')
);

答案 1 :(得分:1)

添加反应路由器Switch仅渲染一个子组件

import {BrowserRouter, Route, Switch} from 'react-router-dom';


<BrowserRouter>

<Switch>
      <Route exact={true} path='/' render={() => (
              <div>
                  <AddDetails />
              </div>
          )}/>
              <Route exact={true} path='details' render={() => (
                  <div>
                     <ShowDetails />
                  </div>
              )}/>
   </div>
</BrowserRouter>

让我知道问题是否仍然存在

答案 2 :(得分:0)

删除路线道具并作为div / Switch的子级传递路线。

检查快速入门: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/guides/quick-start.md