首页 > 解决方案 > 如何在 Typescript 中正确键入 React ErrorBoundary 类组件?

问题描述

这是我目前关于如何ErrorBoundary在 Typescript 中正确键入 React 类组件的尝试:

import React from "react";
import ErrorPage from "./ErrorPage";
import type { Store } from "redux";   // I'M PASSING THE REDUX STORE AS A CUSTOM PROP

interface Props {
  store: Store         // THIS IS A CUSTOM PROP THAT I'M PASSING
}

interface State {      // IS THIS THE CORRECT TYPE FOR THE state ?
  hasError: boolean
}

class ErrorBoundary extends React.Component<Props,State> {
  
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error): State {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo: React.ErrorInfo): void {
    // You can also log the error to an error reporting service
    // logErrorToMyService(error, errorInfo);
    console.log("error: " + error);
    console.log("errorInfo: " + JSON.stringify(errorInfo));
    console.log("componentStack: " + errorInfo.componentStack);
  }

  render(): React.ReactNode {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return(
        <ErrorPage
          message={"Something went wrong..."}
        />
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

这个问题是关于这个ErrorBoundary类组件的类型。我将它分成几部分以使其更容易。


A 部分:道具和状态的类型

我做的对吗?

interface Props {
  store: Store         // THIS IS A CUSTOM PROP THAT I'M PASSING
}

interface State {      // IS THIS THE CORRECT TYPE FOR THE state ?
  hasError: boolean
}

class ErrorBoundary extends React.Component<Props,State> {}

B 部分:getDerivedStateFromError(错误)

error我应该为参数选择什么类型?返回类型应该是State类型吧?

static getDerivedStateFromError(error): State {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

C部分:componentDidCatch(错误,errorInfo:React.React.ErrorInfo)

error我应该为参数选择什么类型?对于errorInfo,React 确实有一个ErrorInfo看起来是正确的类型。是吗?返回类型应该是void,对吗?

componentDidCatch(error, errorInfo: React.ErrorInfo): void {
    console.log("error: " + error);
    console.log("errorInfo: " + JSON.stringify(errorInfo));
    console.log("componentStack: " + errorInfo.componentStack);
}

D 部分:render() 方法

返回类型应该是ReactNode

render(): React.ReactNode {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return(
        <ErrorPage
          message={"Something went wrong..."}
        />
      );
    }

    return this.props.children;
  }

标签: reactjstypescripttypescript-typingsreact-class-based-componentreact-error-boundary

解决方案


您将在文件中获得所有index.d.ts答案@types/react。如果您使用的是 VSCode 之类的 IDE,您可以按住 Ctrl 键并单击一个类型以直接转到其定义。

这是您问题的准确答案,但在此之前,让我建议您更喜欢使用反应hooks而不是类。


由 OP 编辑​​:我从不使用类组件,总是更喜欢函数和钩子,但来自错误边界上的 React文档:

错误边界的工作方式类似于 JavaScript catch {} 块,但适用于组件。只有类组件可以是错误边界。


我给出的行是index.d.ts版本 16.9.49 中的行。

A 部分:是的,就是这样做的。

B 部分:正如您在第 658 行看到的,error是类型any,返回类型是stateor的一部分null

C 部分:在第 641 行,您将看到错误是类型Error,返回类型是void

D 部分:在第 494 行,您可以看到渲染应该返回一个ReactNode...</p>


推荐阅读