reactjs - 'string'.ts 类型上不存在属性'componentStack'
问题描述
我正在使用 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: "",
};
因此,打字稿中存储的errorInfo
内容是string
. componentStack
不能存在,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}
}
推荐阅读
- reactjs - WebPack SyntaxError Unexpected token, expected "," [object Object]
- performance - 在 Jmeter 中如何找到 1k/2k 并发用户的响应时间,以及 1k 和 2k 用户的 Ram-Up 时间
- javascript - 铯如何使用路径位置绘制折线
- html - 从选择选项中选择 HTML 突然消失
- android - Gradle 错误程序类型已存在:org.java_websocket.AbstractWebSocket$1
- flutter - Flutter :- 这个 AdWidget 已经在 Widget 树中。如何禁用此异常。这是什么意思?
- ruby-on-rails - 如何更改 Rails 中无效日期的内置默认 date_select 通知消息?
- azure - 支持在 azure 搜索中上传同义词词典
- c++ - cin 无论如何会影响 c++ 中新关键字的使用吗?
- node.js - Prerender 获取数据的 React 页面