尝试分配给只读 属性 ECMAScript React Native

Attempted to assign to readonly property ECMAScript React Native

我正在尝试为 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
}

}

您的语法不正确。将其添加到构造函数中。

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;
  }
}