如何使用 React-Router 默认显示路由

How to display a Route by default with React-Router

我是 React 新手,想开发一个单页应用,所以我使用的是 react-router 四路由。

在 main.js 下方,我指定了路线

import React from 'react';
import {Router,Route} from 'react-router';
import {App} from './components/App';
import {Login} from './components/Login';
import {Home} from './components/Home';
import { history } from 'react-router';

React.render(
<Router history={history}>
    <Route path="/" component={App}>
        <Route path="home" component={Home}/>
        <Route path="login" component={Login}/>

    </Route>
</Router>,
document.getElementById('main')
);

然后是 App.js,如您所见,我想要一个固定的页眉和页脚,然后让页面内容根据路由动态变化。

import React from 'react';
import {Header} from './Header';
import {Footer} from './Footer';

export class App extends React.Component {


render() {
    console.log(this.props.children);
    return (<div>
        <Header/>
        <div className="page-content">
            {this.props.children}
        </div>
        <Footer/>
    </div>);
}


}

使用此代码,应用程序加载路径(“/”)后,我需要单击 link 主页以显示主页内容,但我希望默认显示, 一旦首次加载应用程序。

我怎样才能做到这一点?

谢谢!!

我认为您可能想使用 React Router 文档中 here 中描述的 IndexRoute

你的路由器看起来像这样:

<Router history={history}>
    <Route path="/" component={App}>
        <IndexRoute component={Home}/>
        <Route path="login" component={Login}/>
    </Route>
</Router>

在嵌套 IndexRoute 时很有用。

<div>
    <Redirect from="/" to="home"/>
    <Route path="/" component={App}>
        <Route path="home" component={Home}>
            <IndexRoute component={IndexView} />
            <Route path="other" component={OtherView}></Route>
        </Route>
        <Route path="about" component={About}></Route>

    </Route>
</div>

react-router 的更高版本中,您可以使用 ÌndexRedirect。这样你就没有义务将你的主屏幕放在路由“/”下。导航到“/”的用户将简单地重定向到“/home”。

<Router history={history}>
    <Route path="/" component={App}>
        <IndexRedirect to="home"/>
        <Route path="home" component={Home}/>
        <Route path="login" component={Login}/>
    </Route>
</Router>