React上的错误根路由

时间:2016-12-10 07:59:17

标签: reactjs routing routes jsx

未捕获错误:根路由必须呈现单个元素。发生这种情况时,我不明白。请告诉我,我不明白的是什么?

menu.jsx:

import React from 'react';
import ReactDOM from 'react-dom';
import { Link } from 'react-router'

class Menu extends React.Component {
   render() {
      return (
         <div>
            <ul>
               <Link to="/">Home</Link>
               <Link to="/contacts">Contacts</Link>
               <Link to="/about">About</Link>
            </ul>               
           {this.props.children}
         </div>
      )
   }
}

about.jsx(等组件):

import React from 'react';

export default class About extends React.Component {
   render() {
      return (
         <div>
            <h1>About...</h1>
         </div>
      )
   }
}

appStart.js

import React from 'react';
import ReactDOM from 'react-dom';

import Home from './app/templates/home';
import About from './app/templates/about';
import Contacts from './app/templates/contacts';

import Menu from './app/layouts/menu';

import { Route, Router, browserHistory, IndexRoute } from "react-router";

ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {Menu}>
         <IndexRoute component = {Home} />
         <Route path = "/home" component = {Home} />
         <Route path = "/about" component = {About} />
         <Route path = "/contacts" component = {Contacts} />
      </Route>
   </Router>

), app)

项目结构:

enter image description here

2 个答案:

答案 0 :(得分:1)

我认为问题出在您的appStart组件中,首先通过document.getElementById()获取html元素,然后在其中呈现组件。试试这个:

ReactDOM.render((
  <Router history = {browserHistory}>
    <Route path = "/" component = {Menu}>
       <IndexRoute component = {Home} />
       <Route path = "/home" component = {Home} />
       <Route path = "/about" component = {About} />
       <Route path = "/contacts" component = {Contacts} />
    </Route>
  </Router>
), document.getElementById("app"))

定义此ID&#34; app&#34;并在您的html页面中包含捆绑文件,如下所示:

<div id="app"/>
<script src = "bundle.js"/>

答案 1 :(得分:1)

可能是因为您在export忘记了menu.jsx您的组件。

export default class Menu extends React.Component {
    // ... rest of the code

同样@ mayank-shukla指出,您应该找到要在DOM中呈现应用的节点。

ReactDOM.render((
  <Router history = {browserHistory}>
    <Route path = "/" component = {Menu}>
       <IndexRoute component = {Home} />
       <Route path = "/home" component = {Home} />
       <Route path = "/about" component = {About} />
       <Route path = "/contacts" component = {Contacts} />
    </Route>
  </Router>
), document.getElementById("app"));

假设您的.html文件类似<div id="app"></div>