【发布时间】:2023-01-28 22:54:47
【问题描述】:
我正在尝试使用 ErrorBoundary 组件在 Typescript 中制作错误捕捉器。坦率地说,我不明白我应该使用什么 props 和 interface 属性来实现与我现在正在学习的 ZTM 课程中的任务相同的目标。最初的任务是在 Javascript 中,但我的目标是在不使用 any 类型的情况下,在 Typescript 中制作相同的应用程序。
我的 render() 方法带有一个自定义的 ErrorBoundary 标记,当这些错误发生在我的 CardList 组件中时,它应该可以捕获错误。 render() 的代码如下:
render() {
const { robots, searchfield } = this.state;
const fileteredRobots = robots.filter(robot => {
return robot.name.toLowerCase().includes(searchfield.toLowerCase())
})
return !robots.length ?
<h1>Loading</h1> :
(
<div className='tc'>
<h1 className='f1'>RoboFriends</h1>
<SearchBox title='search box' searchChange={this.onSearchChange}/>
<ErrorBoundary title='error catcher'>
<Scroll title='scrolling'>
<CardList title='list of robot cards' robots={fileteredRobots} />
</Scroll>
</ErrorBoundary>
</div>
);
}
此代码块中出现的错误说明如下:
Type '{ children: Element; title: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<ErrorBoundary> & Readonly<{ title: string; }>'.
Property 'children' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<ErrorBoundary> & Readonly<{ title: string; }>'.ts(2322)
组件ErrorBoundary的代码来自错误边界.tsx在下面:
import { Component } from "react";
interface IErrorBoundaryProps {
hasError: boolean;
children?: JSX.Element | JSX.Element[];
}
class ErrorBoundary extends Component<{title:string}, IErrorBoundaryProps> {
constructor(props: {title:string}) {
super (props)
this.state = {
hasError: false,
}
}
render () {
if (this.state.hasError) {
return <h1>Ooops. That is an Error</h1>
}
return this.state.children
}
}
export default ErrorBoundary
我修复了来自ErrorBoundary 组件的一些错误,但是我仍然在我的应用程序.tsxrender()方法。
寻找一些建议。
【问题讨论】:
-
请阐明您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
标签: reactjs typescript components