“ Readonly <{}>”类型上的属性不存在

时间:2020-10-20 09:26:49

标签: reactjs

我遇到错误,属性errorOccurred在类型Readonly<{}>上不存在 甚至在google和类似问题的帮助下,我也找不到解决方案。

这是代码:

class ErrorHandler extends React.Component {
    constructor(props) {
        super(props)
        this.state = { errorOccurred: false }
    }

    componentDidCatch(error, info) {
        this.setState({ errorOccurred: true })
    }

    render() {
        return this.state.errorOccurred ? <h1>Something went wrong!</h1> : 
            this.props.children
    }
}

1 个答案:

答案 0 :(得分:0)

似乎您正在使用Typescript,不是吗?

在这种情况下,您必须正确输入组件状态:

interface ErrorHandlerState {
  errorOccurred: boolean;
}
class ErrorHandler extends React.Component<any, ErrorHandlerState> {
  constructor(props) {
    super(props)
    this.state = {
      errorOccurred: false
    }
  }

  componentDidCatch(error, info) {
    this.setState({
      errorOccurred: true
    })
  }

  render() {
    return this.state.errorOccurred ? < h1 > Something went wrong! < /h1> : this.props.children
  }
}