![](/img/trans.png)
[英]Typescript “Cannot assign to property, because it is a constant or read-only” even though property is not marked readonly
[英]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.