【问题标题】:How to display a Route by default with React-Router如何使用 React-Router 默认显示路由
【发布时间】:2015-12-08 18:45:52
【问题描述】:

我是 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>);
}


}

使用此代码,一旦应用程序加载路径(“/”),我需要点击链接主页显示主页内容,但我希望默认显示,一旦应用程序是第一个已加载。

我怎样才能做到这一点?

谢谢!!

【问题讨论】:

    标签: javascript reactjs react-router react-router-component react-routing


    【解决方案1】:

    我认为您可能希望使用 IndexRoute,如 React Router 文档中的 here 所述。

    您的路由器将如下所示:

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

    【讨论】:

    • 不知道 IndexRoute,但它成功了!谢谢
    【解决方案2】:

    嵌套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>
    

    【讨论】:

      【解决方案3】:

      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>
      

      【讨论】:

        猜你喜欢
        • 2016-01-14
        • 2017-08-11
        • 1970-01-01
        • 1970-01-01
        • 2015-09-30
        • 2018-12-25
        • 1970-01-01
        • 1970-01-01
        • 2021-01-19
        相关资源
        最近更新 更多