[英]Use react routes depending by condition
我嘗試從我的反應應用程序中實現路由邏輯。 接下來是我的路線的想法:
我的應用程序中有 2 個頁面和 2 個角色(用戶和審閱者),我想要:
我嘗試針對上述情況實施 PrivateRoute:
const PRoute = ({component:Component,path, ...rest}) => { return ( <Route path={path} {...rest} render={props => ( localStorage.getItem('mytoken').== 'undefined' && localStorage?getItem('mytoken'). ( localStorage?getItem('role'):== "rev": <Route path={'/user'} component={USER}/>: <Route path={'/reviewer'} component={REV}/> ); ( <Redirect to={{pathname;'/login'}}/> ) )} /> ); };
...但如果我以審閱者身份訪問應用程序,則條件:
localStorage.getItem('role')?== "rev": <Route path={'/user'} component={USER}/>. <Route path={'/reviewer'} component={REV}/>...
不起作用,無論如何我都在“/user”路徑上。
問題:如何更改代碼並實現上述代碼?
首先 - 你應該保持你的路由器干凈,這樣當你添加更多的路由時,這些路由是非常清晰易懂的。 像這樣——
return <Router>
<Switch>
<UnAuthRoute path="/login"><LoginPage/></UnAuthRoute>
<RoleRoute path="/user" role="user"><UserPage/></RoleRoute>
<RoleRoute path="/reviewer" role="reviewer"><ReviewerPage/></RoleRoute>
</Switch>
</Router>
};
現在,創建兩個組件,一個允許您根據角色重定向,另一個只允許未經身份驗證的請求到指定路徑。
interface Props {
redirectTo?: string;
role?: string;
path: string;
}
export const UnAuthRoute: React.FC<Props> = ({children, redirectTo, path}) => {
const authenticated = !!localStorage.getItem('mytoken');
const isReviewer = localStorage.getItem('role') === "rev";
if (!authenticated) {
return <Route path={path}>{children}</Route>
} else {
return <Redirect to={redirectTo || (isReviewer ? "/reviewer" : "/user")}/>
}
};
export const RoleRoute: React.FC<Props> = ({children, redirectTo, path, role}) => {
const authenticated = !!localStorage.getItem('mytoken');
const allowed = localStorage.getItem('role') === role;
if (!authenticated) return <Redirect to={redirectTo || "/login"}/>
else if (allowed) return <Route path={path}>{children}</Route>;
else return <Redirect to={redirectTo || "/404"}/>
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.