我刚刚接过一位同事的React项目,但我无法理解下面代码中的逻辑。
content = <Switch>
<Route path="/login" exact component={LoginPage} />
<Route render={() => { return <Redirect to="/login" />; }} />
</Switch>
我知道如何使用Component
的路线,与Render
,但Render
与Redirect
,我第一次见到它。
谢谢
这似乎只是另一种说法:
<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