[英]React protected route
我有以下代碼:
const PrivateRoute = ({ component: Component, ...rest }) => {
return (<Route {...rest} render={(props) => (isAuthenticated() === true ? <Component {...props} /> : <Redirect to='/login' /> )} />)
}
但我不明白這是如何工作的..我稱之為:
<PrivateRoute exact path = '/home' component={Home}></PrivateRoute>
它有效,我只是不明白。 props 是從哪里傳入的? 什么是組件:組件。
如果有人能解釋這個組件是如何工作的,我將不勝感激。
component: Component
是對象解構
您可以通過以下方式重新編寫它:
const PrivateRoute = (props) => {
const Component = props.component;
//shallow copy props, can also do {...props}
const rest = Object.assign({},props);
//delete component property from rest
// this will not affect props becaus of the shallow copy
react-router Route 組件將采用 props.component 並渲染該組件,並使用傳遞給 Route 的所有 props 減去 props.component。
您創建一個PrivateRoute
來執行相同的操作,但不是直接渲染在 props 中傳遞的組件,它會渲染 Route 並將渲染 prop 傳遞給它,這是一個動態創建的組件()=>jsx
。 Route 會為你渲染這個組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.