我正在尝试实现一个具有ProtectedRoute
属性的component
组件-它可以是无状态(纯)组件或正常的React组件。
这些是我的类型:
export interface Props {
isAuthenticated: boolean;
component: React.PureComponent | React.Component;
exact?: boolean;
path: string;
}
这是我的ProtectedRoute组件:
import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import { ROUTES } from '../../constants/routes';
import { Props } from './ProtectedRoute.types';
const ProtectedRoute = (props: Props) => {
const { isAuthenticated, component: Component, ...rest } = props;
return (
<Route
{...rest}
children={props =>
!isAuthenticated ? (
<Redirect to={{ pathname: ROUTES.login, state: { from: props.location } }} />
) : (
<Component {...props} />
)
}
/>
);
};
export default ProtectedRoute;
我在这里遇到以下错误:
类型错误:JSX元素类型“组件”没有任何构造 或致电签名。 TS2604
这是我的用法:
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import ProtectedRoute from './ProtectedRoute';
import { ROUTES } from '../../constants/routes';
import Login from '../Login/Login';
const PlaceholderComponent = () => <div>This is where we will put content.</div>;
const NotFoundPlaceholder = () => <div>404 - Route not found.</div>;
const Routes = () => {
return (
<Switch>
<Route exact path={ROUTES.login} component={Login} />
{/* TODO protected route */}
<ProtectedRoute exact path={ROUTES.list} component={PlaceholderComponent} />
<ProtectedRoute exact path={ROUTES.procedure} component={PlaceholderComponent} />
{/* catchall route for 404 */}
<Route component={NotFoundPlaceholder} />
</Switch>
);
};
export default Routes;
和此处得到以下错误:
类型'()=>元素'不可分配给类型'PureComponent <{},{}, 任何> |组件<{},{},any>'。输入“()=>元素”是缺少 类型'Component <{},{},any>'的以下属性:上下文, setState,forceUpdate,render等3个。 [2322]
这让我觉得,我现在用的是不正确的类型定义。什么是“正确”的方式来进行此事?我的目的是检查ProtectedRoute
始终获得一个React组件作为component
道具。
答案 0 :(得分:1)
功能组件和类组件的类型均为ComponentType
。
应该是:
export interface Props {
isAuthenticated: boolean;
component: React.ComponentType;
exact?: boolean;
path: string;
}
答案 1 :(得分:0)
可能找到了它,但是由于我不知道这是否是正确的解决方案,因此将其保留为空:
export interface Props {
isAuthenticated: boolean;
component: React.ComponentClass<any> | React.StatelessComponent<any>;
exact?: boolean;
path: string;
}