ReactRouter v4 - 重定向不适用于Switch

时间:2017-03-18 15:05:12

标签: reactjs redirect react-router

我有一个代码:

import React from 'react';
import ReactDOM from 'react-dom';
import Navigation from './Navigation';
import PublicPage from './PublicPage';
import LoginPage from './LoginPage';
import SecuredPage from './SecuredPage';
import {Route, Switch, Redirect, BrowserRouter} from 'react-router-dom';

ReactDOM.render(
    <BrowserRouter>
        <Navigation>
            <Switch>
                <Redirect from='/' to='/public'/>
                <Route path="/public" component={PublicPage}/>
                <Route path="/login" component={LoginPage}/>
                <Route path="/secured" component={SecuredPage}/>
            </Switch>
        </Navigation>
    </BrowserRouter>,
    document.getElementById("react-app")
);

现在我希望路径/重定向到/public路径,但不知道这种配置无法正常工作。其他路线也会停止渲染。我想我会在documentation

中做所有事情

2 个答案:

答案 0 :(得分:9)

交换

<Redirect from='/' to='/public'/>

<Redirect exact from='/' to='/public'/>

因为否则&#39; /&#39;将匹配所有内容,创建无限重定向循环

答案 1 :(得分:3)

对于rafty回答的补充还有另一种解决方案:

ReactDOM.render(
    <BrowserRouter>
        <Navigation>
            <Switch>
                <Route exact path="/">
                    <Redirect from='/' to='/public'/>
                </Route>
                <Route path="/public" component={PublicPage}/>
                <Route path="/login" component={LoginPage}/>
                <Route path="/secured" component={SecuredPage}/>
            </Switch>
        </Navigation>
    </BrowserRouter>,
    document.getElementById("react-app")
);

但当然不那么干净。