首页 > 解决方案 > 如何防止未经授权的用户使用反应路由访问页面

问题描述

我正在开发带有 typescript 应用程序的 React,并希望防止未经身份验证的用户访问某些页面。

到目前为止,我有这个:

import { Redirect, Route, RouteProps } from 'react-router'

export interface ProtectedRouteProps extends RouteProps {
  isAuthenticated: boolean
  isAllowed: boolean
  restrictedPath: string
  authenticationPath: string
}

export const ProtectedRoute = (props: ProtectedRouteProps) => {
  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

出于某种原因,Typescript 在这些行抛出一些编译错误:

  if (redirectPath) {
    const renderComponent = () => <Redirect to={{ pathname: redirectPath }} />
    return <Route {...props} component={renderComponent} render={undefined} />
  } else {
    return <Route {...props} />
  }

重定向显示:(别名)类重定向导入重定向解析错误:“>”预期。

redirectPath显示: const redirectPath: any Binding element 'redirectPath' 隐含一个 'any' 类型

else stm 中的路由显示:算术运算的左侧必须是“any”、“number”、“bigint”类型或枚举类型。ts(2362)

更新:我的 package.json 没有 react-router 但有 react-router-dom 这可能是问题吗?

标签: javascriptreactjstypescript

解决方案


您的文件名为 ProtectedRoute.ts 还是 ProtectedRoute.tsx?我尝试运行您的代码,当我使用 .tsx 文件类型重命名我的文件时,错误消失了。

重新 package.json react-router-dom 是您需要的正确包。react-router 在 react-router-dom 的底层使用。

还要确保你使用npm i @types/react-router-dom


推荐阅读