首页 > 解决方案 > 如何为反应私有路由器组件添加类型?

问题描述

我想为身份验证用户添加私有路由器。并找到带有私有路由器组件的简单解决方案,但打字稿返回我类型错误。我尝试添加任何类型,但这无济于事。我如何在这里添加类型?

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);

标签: reactjstypescriptreact-routerreact-router-v4

解决方案


当您使用 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 } }} />}
        />
    )
}




推荐阅读