javascript - 如何防止未经授权的用户使用反应路由访问页面
问题描述
我正在开发带有 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 这可能是问题吗?
解决方案
您的文件名为 ProtectedRoute.ts 还是 ProtectedRoute.tsx?我尝试运行您的代码,当我使用 .tsx 文件类型重命名我的文件时,错误消失了。
重新 package.json react-router-dom 是您需要的正确包。react-router 在 react-router-dom 的底层使用。
还要确保你使用npm i @types/react-router-dom
推荐阅读
- javascript - 使用 useEffect() 复制 componentDidMount 逻辑以在客户端加载外部 JavaScript
- python - 比较两个音频文件的信号的功能
- python - pygame 不使用按键更新 draw.rect,即使 x 和 y 值正在更新
- python - 如何从网站上抓取项目名称,同时进入一个循环输入项目链接并解析描述?
- android - 错误 I/zygote (11430) 是什么意思?
- c# - 如何从一个集合中一次取两个
- python - ImportError:无法导入名称“MaxPooling2D”
- flutter - 遍历包含多个项目的地图
- angular - 一旦 ngIf 变为真,如何将数据从父级重新发送给子级?
- python - 在 HTML 页面中嵌入作为 HTML 的 Python 输出