属性 'componentStack' 在类型 'string' 上不存在。ts

Property 'componentStack' does not exist on type 'string'.ts

我正在使用 Typescript 和 React 实现 ErrorBoundary

TSLint 显示错误 Property 'componentStack' does not exist on type 'string'

这是我的代码实现

interface IState {
  info: ErrorInfo;
}

  public state = {
    errorInfo: "",
  };

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    this.setState({
      errorInfo
    });
  }
  public render() {
    if (this.state.errorInfo) {
      return (
          <p>
            {this.state.errorInfo.componentStack}
          </p>
      );
    }
  }

您在此处隐式声明 errorInfo 为字符串:

public state = {
    errorInfo: "",
};

所以对于 typescript,存储在 errorInfo 中的是一个 stringcomponentStack 不能存在于 string 中,这就是你得到错误的原因。

你应该这样声明:

public state: {
   errorInfo: string | { componentStack: Function, },
} = {
    errorInfo: "",
};

并完成对 state 对象内部内容的描述。

如果不知道就用any

public state: any = {
    errorInfo: "",
};

无论如何你应该在调用它之前测试 componentStack 是否存在,以防 errorInfo 确实是一个空的 string.

if (this.state.errorInfo && typeof this.state.errorInfo.componentStack === 'Function') {
    {this.state.errorInfo.componentStack}
}