使用react-router-dom路由+渲染+重定向

问题描述 投票:0回答:1

我刚刚接过一位同事的React项目,但我无法理解下面代码中的逻辑。

      content = <Switch>
        <Route path="/login" exact component={LoginPage} />
        <Route render={() => { return <Redirect to="/login" />; }} />
      </Switch>

我知道如何使用Component的路线,与Render,但RenderRedirect,我第一次见到它。

谢谢

reactjs react-router-dom
1个回答
1
投票

这似乎只是另一种说法:

<Redirect path='*' to='/login' />

因为它在<Switch>内部,并且在任何<Route>之后,它将始终匹配(如果它上面没有任何匹配)并且被渲染。

Redirect组件被渲染时,它会重定向到to prop中指定的页面。

我通过做一些源代码的阅读发现了这一点。如果你感兴趣的话,有一些间接,但基本上Redirect组件呈现一个Lifecycle组件,它会在method安装后立即调用location

method设置如下:

const method = push ? history.push : history.replace;

这就是这样做的,因为显然<Redirect>组件可以将push作为布尔道具来设置重定向实际实现的行为。


重定向组件源https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Redirect.js

生命周期组件来源:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Lifecycle.js

© www.soinside.com 2019 - 2024. All rights reserved.