如何为专用路由器组件添加类型?

时间:2019-06-15 13:30:54

标签: reactjs typescript react-router react-router-v4

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

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;

PrivateRouter

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

1 个答案:

答案 0 :(得分:-1)

  

当您使用type时,会破坏打字稿的味道。

现在,查看您的代码,我想您希望根据prop中auth的值将用户带到特定路径。所有其余的道具应该与react-router相同。

我在您的代码中看到的一个明显错误是,您正在接收每个prop作为功能组件中的参数,但是它只接收一个参数,即props对象。

所以在您的方法中,应该是

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 } }} />}
        />
    )
}