首页 > 解决方案 > 无法分配给“状态”,因为它是常量或只读属性

问题描述

当我对这个问题进行搜索时,我只能找到this.state直接在方法体中某处修改的问题,而不是使用this.setState(). 我的问题是我想在构造函数中设置一个起始状态,如下所示:

export default class Square extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      active: false
    };
  }

  public render() {
    ...
  }
}

该应用程序无法启动,并出现以下编译错误:

Cannot assign to 'state' because it is a constant or a read-only property

这是因为在定义中React.Component我们有:

readonly state: null | Readonly<S>;

所以我不知道该怎么做。JS 中的官方反应教程直接分配给this.state并说在构造函数中这样做是一种可接受的模式,但我无法弄清楚如何使用 TypeScript 来做到这一点。

标签: reactjstypescripttypes

解决方案


在回滚之前(如@torvin 的回答所建议),请通读https://github.com/DefinitelyTyped/DefinitelyTyped/pull/26813#issuecomment-400795486

这并不意味着回归 - 解决方案是state用作属性。它比以前的方法(state在构造函数中设置)要好,因为:

  • 你不再需要构造函数了
  • 你不能忘记初始化状态(现在是编译时错误)

例如:

type Props {}

type State {
  active: boolean
}

export default class Square extends React.Component<Props, State> {
  public readonly state: State = {
    active: false
  }

  public render() {
    //...
  }
}

另一种方法:

type Props {}

const InitialState = {
  active: false
}

type State = typeof InitialState

export default class Square extends React.Component<Props, State> {
  public readonly state = InitialState

  public render() {
    //...
  }
}

推荐阅读