簡體   English   中英

無法分配給“狀態”,因為它是常量或只讀屬性

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

當我搜索這個問題時,我只能找到直接在方法體的某個地方修改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 中的官方 react 教程直接賦值給this.state並說在構造函數中這樣做是可以接受的模式,但我無法弄清楚如何用 TypeScript 來做到這一點。

在回滾之前(如@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() {
    //...
  }
}

考慮到 Typescript不支持在派生構造函數中分配父級的只讀字段這一事實,這似乎是在提交542f3c0中引入的@types/react的最新更改,但效果不佳。

我建議回滾到@types/react的先前版本。 版本16.4.2似乎是進行不幸更改之前的最后一個版本。

您可以通過刪除package.json^來固定版本:

"devDependencies": {
  ...
  "@types/react": "16.4.2",

另請查看關於此更改的討論絕對類型 github 拉請求頁面

因為state是組件的只讀屬性,所以不能逐個字段設置,但你仍然可以這樣做:

constructor(props: MyProps) {
  super(props);
  this.state = {
    // include properties here
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM