我正在尝试为我Component
中声明的数组赋值。不幸的是,抛出异常。
TypeError: Attempted to assign to readonly property
即使我删除strict
模式,仍然会引发异常。可以请某人指导我如何使变量既可读又可写?谢谢..!
代码:
class RootView extends Component {
cachedData : []; //declared array here
//trying to assign dictionary in some function
someFunction(results) {
this.cachedData[this.state.searchString.length - 1] = results;
//exception raised here
}
}
答案 0 :(得分:5)
您的语法不正确。将其添加到构造函数中。
class RootView extends Component {
constructor() {
super();
this.cachedData = [];
}
someFunction(results) {
this.cachedData[this.state.searchString.length - 1] = results;
}
}
如果您的转发器支持experimental code(第0阶段),您可以使用以下内容:
class RootView extends Component {
cachedData = [];
someFunction(results) {
this.cachedData[this.state.searchString.length - 1] = results;
}
}