我试图实现一个ProtectedRoad
组件,它有一个组件
prop-它可以是无状态(纯)组件或正常的反应组件。
以下是我的类型:
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元素类型“Component”没有任何构造或调用签名。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;
并在此处获取以下错误:
键入“()=
这让我认为我使用了不正确的类型定义。这件事的“正确”方式是什么?我的目的是检查ProtectedRoad
是否总是得到一个React组件作为组件
道具。
功能组件和类组件的类型都是ComponentType
。
应该是:
export interface Props {
isAuthenticated: boolean;
component: React.ComponentType;
exact?: boolean;
path: string;
}
可能找到了,但会将其打开,因为我不知道这是否是正确的解决方案:
export interface Props {
isAuthenticated: boolean;
component: React.ComponentClass<any> | React.StatelessComponent<any>;
exact?: boolean;
path: string;
}