reactjs - 如何为反应私有路由器组件添加类型?
问题描述
我想为身份验证用户添加私有路由器。并找到带有私有路由器组件的简单解决方案,但打字稿返回我类型错误。我尝试添加任何类型,但这无济于事。我如何在这里添加类型?
Error:(18, 18) TS2322: Type '{ exact: true; path: string; component: typeof Main; }' is not assignable to type 'IntrinsicAttributes & Component<any, any, any>'.
Property 'exact' does not exist on type 'IntrinsicAttributes & Component<any, any, any>'.
路由器
import { Route, Switch } from 'react-router-dom';
import React, { Component } from 'react';
import app from 'firebase/app';
import Main from "src/Templates/Main/Main.container";
import Login from "src/Templates/Login/Container/Login";
import PrivateRoute from "src/Core/Routers/PrivateRoute";
import {withFirebase} from "src/Templates/Firebase";
class Routes extends Component<any, any> {
render() {
return (
<Switch>
<PrivateRoute exact path='/' component={Main} />
<Route exact path='/login' component={Login} />
</Switch>
)
}
}
export default Routes;
私人路由器
import React, {Component} from 'react';
import { Redirect, Route } from 'react-router-dom';
const PrivateRoute = (component: Component<any, any>, { ...rest }: any): any => (
<Route {...rest} render={(props: any) => (
props.auth !== null ? (
<Component {...props} />
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}
/>
)
)} />
);
//withFirebase() its my HOC fabric component, with provides props for check auth user.
export default withFirebase(PrivateRoute);
解决方案
当您使用 type as any 时,您正在破坏 typescript 的味道。
现在,查看您的代码,我认为您希望根据道具中 auth 的值将用户带到特定路径。并且所有剩余的道具应该与 react-router 相同。
我可以在您的代码中看到一个明显的错误是您正在接收每个道具作为功能组件中的参数,但它只接收一个参数,即道具对象。
所以在你的方法中,它应该是,
const PrivateRoute = (props: any): any => ()
现在,一种更清洁、更好的方法是:
import React, {Component} from 'react';
import { RouteProps, Route, Redirect } from 'react-router-dom';
export interface PrivateRouteProps extends RouteProps {
auth: boolean | null
}
function PrivateRoute({ component: Component, auth, ...rest }: PrivateRouteProps) {
return (
<Route
{...rest}
render={(props) => auth !== true
? <Component {...props} />
: <Redirect to={{ pathname: '/login', state: { from: props.location } }} />}
/>
)
}
推荐阅读
- sql - 根据日期选择下一个位置
- android - 当我在底部导航的屏幕之间导航时,我的颤振应用程序不断重建自身
- javascript - javascript 类方法应该决定它们是否执行,还是被调用者决定是否调用?
- sharepoint - SharePoint Online 工作流 IP 地址
- java - 在java8中添加两个列表?
- python - 如何查找在 Panda 数据框中每个位置花费的时间?
- httprequest - SapUI5 odata v4 调用函数报错“未知操作”
- algorithm - log(n)=O(n^1/100) 的 n_0 是多少?
- php - Laravel 8 - Handle errors on PUT form request
- javascript - JS Promises 按顺序解决?