【问题标题】:react, typescript - a type for both stateless and normal componentsreact, typescript - 无状态组件和普通组件的类型
【发布时间】:2019-01-30 09:51:52
【问题描述】:

我正在尝试实现具有 component 属性的 ProtectedRoute 组件 - 它可以是无状态(纯)组件或普通反应组件。

这些是我的类型:

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;

并在此处收到以下错误:

Type '() => Element' 不可分配给 type 'PureComponent |组件'。类型 '() => Element' 缺少 'Component' 类型的以下属性:上下文, setState、forceUpdate、render 和另外 3 个。 [2322]

这让我觉得我使用了不正确的类型定义。解决这个问题的“正确”方法是什么?我的目的是检查 ProtectedRoute 是否总是获得一个 React 组件作为 component 属性。

【问题讨论】:

  • typescript 标签如何链接到 react 主题?没有意义
  • 它是来自打字稿文件的打字稿错误,关于类型定义?
  • “TypeScript 是 Microsoft 创建的 JavaScript 的类型化超集” - 据我所知,该标签用于 typescript 语法,但在您的情况下,错误是在您使用的库或包中引发的。我认为最好指定 lib/package 的标签而不是 typescript。是吗?

标签: javascript reactjs typescript


【解决方案1】:

函数和类组件的类型是ComponentType

应该是:

export interface Props {
  isAuthenticated: boolean;
  component: React.ComponentType;
  exact?: boolean;
  path: string;
}

【讨论】:

    【解决方案2】:

    可能找到了,但会保持打开状态,因为我不知道这是否是正确的解决方案:

    export interface Props {
      isAuthenticated: boolean;
      component: React.ComponentClass<any> | React.StatelessComponent<any>;
      exact?: boolean;
      path: string;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-23
      • 2020-08-12
      • 2022-12-11
      • 2018-11-29
      • 2020-05-25
      • 2016-04-17
      • 2017-11-28
      • 1970-01-01
      • 2016-12-17
      相关资源
      最近更新 更多