React Router无法在简单的应用程序中工作,显示空白页面

时间:2017-03-21 15:56:45

标签: reactjs react-router

我对React很新,我正在尝试做一个简单的React应用程序。 我使用create-react-app创建了我的项目。 但我在实施路由器时遇到问题。 这是我的index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';

class App extends React.Component {
   render() {
      return (
         <div>
            <ul>
               <li>Home</li>
               <li>About</li>
               <li>Contact</li>
            </ul>

            {this.props.children}

         </div>
      );
   }
}

class Home extends React.Component {
   render() {
      return (
         <div>
            <h1>Home...</h1>
         </div>
      );
   }
}

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

class Contact extends React.Component {
   render() {
      return (
         <div>
            <h1>Contact...</h1>
         </div>
      );
   }
}

ReactDOM.render(
  <Router history={browserHistory}>
      <Route path="/" component={App}>
        <IndexRoute path="home" component={Home}/>
        <Route path="about" component={About}/>
        <Route path="contact" component={Contact}/>
      </Route>
   </Router>,
  document.getElementById('root')
);

当我运行我的应用时,它会显示一个空白页面,而不会给我任何错误/警告,如下图所示:

React app blank Page

我理解反应路由器的简单使用,但我仍然无法理解我的代码有什么问题。有任何想法吗?谢谢你的回答

2 个答案:

答案 0 :(得分:1)

正如Fabian Schultz所说,由于我使用的是react-router 4.0.0,我应该使用react-router-dom包。这解决了我的问题。

答案 1 :(得分:-1)

您不应在IndexRoute组件中使用path属性,因为它相对于其父级。我正在编写一个简单而干净的React样板文件,您可以在我的https://github.com/marcj/css-element-queries/issues/31页面中查看它。

要解决您的问题,您可以使用此<IndexRoute path="home" component={Home}/>替换此<IndexRoute component={Home}/>

在这种情况下,IndexRoute将使用父路径,即&#34; /&#34;。

还有一件事,我建议您使用组件<Link />而不是默认锚点。这样,您可以轻松地为链接设置活动类。看看吧。

import { IndexLink, Link } from 'react-router';

class App extends React.Component {
   render() {
      return (
         <div>
            <ul>
               <IndexLink to='/' className='anchor' activeClassName='anchor--active'>Home</Link></li>
               <Link to="/about" className='anchor' activeClassName='anchor--active'>About</Link></li>
               <Link to="/contact" className='anchor' activeClassName='anchor--active'>Contact</Link></li>
            </ul>

            {this.props.children}

         </div>
      );
   }
}

希望它有所帮助。