栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用TypeScript和React-Router 4和5重写受保护/专用路由?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用TypeScript和React-Router 4和5重写受保护/专用路由?

该错误可能与打字和渲染中的隐式返回有关。解决此问题时,最终会得到如下结果:

const PrivateRoute = ({component, isAuthenticated, ...rest}: any) => {    const routeComponent = (props: any) => (        isAuthenticated ? React.createElement(component, props) : <Redirect to={{pathname: '/login'}}/>    );    return <Route {...rest} render={routeComponent}/>;};

该组件可以这样使用:

<PrivateRoute    path='/private'    isAuthenticated={this.props.state.session.isAuthenticated}    component={PrivateContainer}/>

上面的解决方案有一些缺点。其中之一是您失去类型安全性。

最好扩展

Route
组件是更好的主意。

import * as React from 'react';import {Redirect, Route, RouteProps} from 'react-router';export interface ProtectedRouteProps extends RouteProps {    isAuthenticated: boolean;    authenticationPath: string;}export class ProtectedRoute extends Route<ProtectedRouteProps> {    public render() {        let redirectPath: string = '';        if (!this.props.isAuthenticated) { redirectPath = this.props.authenticationPath;        }        if (redirectPath) { const renderComponent = () => (<Redirect to={{pathname: redirectPath}}/>); return <Route {...this.props} component={renderComponent} render={undefined}/>;        } else { return <Route {...this.props}/>;        }    }}

因此,您可以使用以下组件:

const defaultProtectedRouteProps: ProtectedRouteProps = {    isAuthenticated: this.props.state.session.isAuthenticated,    authenticationPath: '/login',};<ProtectedRoute    {...defaultProtectedRouteProps}    exact={true}    path='/'    component={ProtectedContainer}/>

更新(2019年11月)

如果您喜欢编写功能组件,则可以采用非常相似的方式来完成。这也适用于React Router 5:

import * as React from 'react';import { Redirect, Route, RouteProps } from 'react-router';export interface ProtectedRouteProps extends RouteProps {  isAuthenticated: boolean;  isAllowed: boolean;  restrictedPath: string;  authenticationPath: string;}export const ProtectedRoute: React.FC<ProtectedRouteProps> = props => {  let redirectPath = '';  if (!props.isAuthenticated) {    redirectPath = props.authenticationPath;  }  if (props.isAuthenticated && !props.isAllowed) {    redirectPath = props.restrictedPath;  }  if (redirectPath) {    const renderComponent = () => <Redirect to={{ pathname: redirectPath }} />;    return <Route {...props} component={renderComponent} render={undefined} />;  } else {    return <Route {...props} />;  }};export default ProtectedRoute;

更新(2019年12月)

如果要将用户重定向到该用户首先要访问的路径,则需要记住该路径,这样您就可以在成功通过身份验证后进行重定向。以下答案将指导您完成该任务:



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/418051.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号