gpt4 book ai didi

reactjs - 无法分配给 'state',因为它是常量或只读属性

转载 作者:搜寻专家 更新时间:2023-10-30 20:29:31 27 4
gpt4 key购买 nike

当我搜索这个问题时,我只能找到直接在方法体某处修改 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 作为 property。它比以前的方法(在构造函数中设置 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() {
//...
}
}

关于reactjs - 无法分配给 'state',因为它是常量或只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51074355/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com