我正在练习打字稿,我遇到了一个不允许我继续前进的错误:Property 'isMounted' does not exist on type 'ErrorBoundary'。
我有以下边界组件
// React
import React from 'react'
// Librarys
import ReportIcon from '@mui/icons-material/Report';
type ChildrenProp = {
children: React.ReactNode,
}
type BoundaryState = {
error: null|string
}
export default class ErrorBoundary extends React.PureComponent<ChildrenProp, BoundaryState> {
constructor(props:ChildrenProp) {
super(props)
this.isMounted = false
this.state = {
error: null,
}
}
componentDidMount() {
this.isMounted = true
}
componentDidCatch(error) {
this.isMounted && this.setState({ error: error.message })
}
componentWillUnmount() {
this.isMounted = false
}
render() {
if (this.state.error) {
return (
<div className="d-flex h-100 align-items-center justify-content-center flex-column text-muted text-center">
<ReportIcon className="mb-1 fs-4" />
<h4 className="text-secondary">Application Error:</h4>
<code className="col-10 mx-auto">{JSON.stringify(this.state.error)}</code>
</div>
)
}
return this.props.children
}
}
我需要理解为什么类型记录会抛出此错误,this.isMounted是导致此错误的原因,但是如何分配类型呢?非常感谢
发布于 2022-05-13 23:53:47
将public isMounted: boolean;添加到组件以声明它( public是可选的)
export default class ErrorBoundary extends React.PureComponent<ChildrenProp, BoundaryState> {
public isMounted: boolean;
constructor(props:ChildrenProp) {
...
}https://stackoverflow.com/questions/72236299
复制相似问题