reactjs - 无法分配给“状态”,因为它是常量或只读属性
问题描述
当我对这个问题进行搜索时,我只能找到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 来做到这一点。
解决方案
在回滚之前(如@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() {
//...
}
}
推荐阅读
- c++ - 'char **':dynamic_cast 的目标类型无效
- gcc - GCC 上 x86 intel asm 中方括号前的偏移量
- mysql - 我的 SQL 数据库不一致(基数与自动增量)
- java - 如何在 sublime text 3 中为 java 构建系统,它也支持包?
- c# - EF Core - 如何在包含的集合中包含项目的集合
- javascript - 如何在javascript中将字符串数组转换为数字数组?
- mysql - 从 Mysql 表中选择数字范围之间的下一个空闲数字
- php - Validate() 消息在 laravel 中不起作用
- ios - MFMailComposeViewController 不会将变量读入 Swift 中的消息
- docker - Docker-compose 将一个服务的标准输出传递给另一个服务的标准输入