【问题标题】:TypeScript error on an ErrorBoundary component connected with Redux (mapStateToProps)与 Redux (mapStateToProps) 连接的 ErrorBoundary 组件上的 TypeScript 错误
【发布时间】:2021-04-26 08:22:33
【问题描述】:

我在 React/ErrorBoundary 组件上遇到类型问题,指出 “typeof ErrorBoundary”类型的参数不能分配给“ComponentType”类型的参数 从不 >'.

澄清一下:我使用 mapStateToProps 将其与商店中设置的用户语言首选项联系起来。

这是我的组件

interface ErrorTexts {
  texts: ErrorTextType;
}

interface Props {
  children: ReactNode | ReactNode[];
  texts: ErrorTextType;
}

interface State {
  error: Error | null;
}

class ErrorBoundary extends Component<Props, State> {
  static propTypes = {
    children: node,
    texts: errorTextsPropType
  };

  static defaultProps = {
    children: null,
    texts: defaultTexts.en.error
  };

  state: State = {
    error: null
  };

  static getDerivedStateFromError(error: Error): State {
    return { error };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('Something unexpected had happened', error, errorInfo);
  }

  render() {
    const { error }: { error: Error | null } = this.state;
    const { texts }: ErrorTexts = this.props;

    if (error) {
      return <ErrorComponent error={error.message} texts={texts} />;
    }
    return this.props.children;
  }
}

const mapStateToProps = (state: AppState): ErrorTexts => ({
  texts: state.texts.error
});

export default connect(mapStateToProps)(ErrorBoundary);

作为参考,这些是我导入的 ErrorText 类型:

export interface ErrorTextType {
  errorLine1: string;
  errorLine2: string;
  notifyMe: string;
  title: string;
}

export const errorTextsPropType = shape({
  errorLine1: string.isRequired,
  errorLine2: string.isRequired,
  notifyMe: string.isRequired,
  title: string.isRequired
});

因此,在母组件上,我遇到了一个错误这个 JSX 标签的 'children' 属性需要一个类型为 'never' 的子元素,但提供了多个孩子。

关于如何解决这个问题的任何想法? :/

【问题讨论】:

  • 删除static propTypes。您已经在使用 TypeScript,因此您不需要 propTypes 进行类型检查。阅读docs
  • @ajeet-shah 我想我不同意这一点。这里的 PropTypes 帮助我在运行时使用我的道具。正如here 所讨论的,TypeScript 和 PropTypes 在代码上有不同的用途。

标签: reactjs typescript react-redux react-typescript react-error-boundary


【解决方案1】:

不用单独写接口Props,使用InferProps泛型来推断prop类型:

import PropTypes, { shape, InferProps} from "prop-types";

class ErrorBoundary extends Component<InferProps<typeof ErrorBoundary.propTypes>, State> {
  static propTypes = {
    children: PropTypes.node,
    texts: errorTextsPropType,
  };

【讨论】:

    猜你喜欢
    • 2019-01-09
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    相关资源
    最近更新 更多