constructor中初始化state值
来源:3-11 【概念理解】State vs Props

Zhang_Kyra
2021-06-20
老师您好,既然能在constructor中初始化state的值,为什么 this.state.isOpen = false的写法会报错。
constructor(props: Props) {
super(props);
this.state.isOpen = false;//error Cannot assign to ‘isOpen’ because it is a read-only property.
this.state =
{
isOpen: false,
};
}
写回答
1回答
-
报错信息说,“isOpen是个只读的属性,不能直接赋值”。
关于如何在constructor中给state进行初始化,在react官方文档中说得很明确,1. 初始化state不能使用setState(); 2. 需要通过对象(也就是花括号 { })来赋值。
https://zh-hans.reactjs.org/docs/react-component.html#constructor
这就是为什么我们不能直接使用 "this.state.isOpen = false" 这种方式
012021-06-22
相似问题