我正在try 做一个错误捕捉器在打字脚本,使用ErrorBoundary
组件.坦率地说,我不明白,我应该使用什么props
和interface
属性来实现与我现在正在学习的ZTM课程的任务中表示的目标相同的目标.最初的任务是在脚本,然而我的目标是使相同的应用程序的类型,而不是使用any
类型.
我的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中的组件ErrorBoundary
的代码如下:
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
组件中的一些错误,但是在我的App.tsx render()
方法中仍然得到了上面的错误.
我的主要问题是:如何修复我的render()
方法中发生的错误?