简体   繁体   English

如何在 React 中创建默认路由?

[英]How can I make default route in React?

I am trying to make default route in my routes.js file using react-router-dom package.我正在尝试使用react-router-dom包在我的 routes.js 文件中创建默认路由。

This is my code:这是我的代码:

import React from 'react';
import { Route, Switch, Router, Redirect, BrowserRouter } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import MainContainer from './containers/main';

const Routes = () => (
    <BrowserRouter>
        <Switch>
            <Route path='/' component={MainContainer} />
            <Redirect from='/' exact to='/main'/>
        </Switch>
    </BrowserRouter>
);

export default Routes;

But it doesn't redirect / to /main .但它不会将/重定向到/main Basically, whenever user goes to / it should redirect to /main .基本上,每当用户转到/它应该重定向到/main Also, the /main should be starting point (homepage) when I build my app.此外, /main应该是我构建应用程序时的起点(主页)。 I am using create-react-app boilerplate CLI .我正在使用create-react-app 样板 CLI

Thanks.谢谢。

To get the effect that you want, you should, first of all, move the Redirect to the top of the Switch .要获得您想要的效果,您首先应该将Redirect移动到Switch的顶部。

Second, you have to change the "to" property for your Route to /main .其次,您必须将Route的“to”属性更改为/main Since that is the location that you want to load your MainContainer component for.因为这是您要为其加载MainContainer组件的位置。

Like so:像这样:

import React from 'react';
import { Route, Switch, Router, Redirect, BrowserRouter } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import MainContainer from './containers/main';

const Routes = () => (
    <BrowserRouter>
        <Switch>
            <Redirect exact from='/' to='/main'/>
            <Route path='/main' component={MainContainer} />
        </Switch>
    </BrowserRouter>
);

export default Routes;

In the code you posted, all locations go to the Route component because they all contain / .在您发布的代码中,所有位置都转到Route组件,因为它们都包含/ So the switch will never hit the Redirect .所以 switch 永远不会击中Redirect

In my example, the Redirect will get hit when the location is exactly / .在我的示例中,当位置正好是/时,重定向将被命中。 It will then redirect the user to /main , where the Switch will hit the Route which loads your MainContainer component.然后它将用户重定向到/main ,其中Switch将点击加载MainContainer组件的Route

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM