【问题标题】:Property does not exist on type 'Readonly<{}>' [duplicate]类型“只读<{}>”上不存在属性[重复]
【发布时间】:2021-02-03 02:40:41
【问题描述】:

我收到错误属性 errorOccurred 在类型 Readonly&lt;{}&gt; 上不存在 即使在谷歌和类似问题的帮助下,我也找不到解决方案。

代码如下:

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
    }
}

【问题讨论】:

  • 定义组件时不提供通用属性或状态类型。
  • 在我看来您使用的是 TypeScript,但您还没有定义组件状态的类型。
  • 如果将示例代码放在codesandbox 中,则非常适合调试。

标签: reactjs


【解决方案1】:

您好像在使用 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
  }
}

【讨论】:

    猜你喜欢
    • 2020-05-03
    • 2018-12-04
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 2020-01-29
    • 2023-03-31
    相关资源
    最近更新 更多