React Router v4嵌套路由不起作用

时间:2017-10-09 09:03:07

标签: reactjs react-router react-router-v4

我刚刚使用基于Fountain JS的样板的react 15.4.2 app升级到React Router v4,在阅读this article之后,我写道:

// Index.js
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import {Route, BrowserRouter, Switch} from 'react-router-dom';
import {Main} from './app/pages/main';
import {App} from './app/pages/app';

import './index.scss';
const MainRouter = () => (
<div>
<main>
      <Switch>
        <Route path="/home" component={Main}/>
        <Route path="/app" component={App}/>
      </Switch>
    </main>
  </div>
);

ReactDOM.render(
  <BrowserRouter>
    <MainRouter/>
  </BrowserRouter>,
  document.getElementById('root')
 );

// App.jsx
import React, {Component} from 'react';
import {Switch, Route} from 'react-router-dom';
import PropTypes from 'prop-types';
import {Dashboard} from './app/dashboard';
import {Money} from './app/money';
import {Header} from '../tpl/header';
import {Footer} from '../tpl/footer';

export class App extends Component {

render() {

return (
  <div>
    <Header/>
    <main>
      <Switch>

            <Route path="/app/dashboard" exact component={Dashboard}/>
            <Route path="/app/money" exact component={Money}/>
          </Switch>
        </main>
        <Footer/>
      </div>
    );
  }
}

// dashboard.jsx
import React, {Component} from 'react';

export class Dashboard extends Component {
  render() {
    return (
      <div>
        <h1>This is the Dashboard</h1>
      </div>
    );
  }
}

导航到http://localhost:3000/app/似乎工作正常,但导航到http://localhost:3000/app/dashboard会给出404.我可能会出错?

PS即使在有效的路线上,添加尾部斜线也不起作用。

1 个答案:

答案 0 :(得分:0)

您需要在App的渲染结束时更正仪表板路线。 不需要另一个Switch那边。所以在你的App.jsx文件的渲染方法中:

render() {
  return (
    <div>
      ...
      <Route path="/app/dashboard" component={Dashboard}/>
    </div>
  );
}