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

Nig*_*ury 2 ecmascript-6 react-native

我试图为我声明的数组赋值Component.不幸的是,抛出异常.

TypeError: Attempted to assign to readonly property
Run Code Online (Sandbox Code Playgroud)

即使我删除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
}

}
Run Code Online (Sandbox Code Playgroud)

Ben*_*une 5

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

class RootView extends Component {

  constructor() {
    super();
    this.cachedData = [];
  }
  someFunction(results) {
    this.cachedData[this.state.searchString.length - 1] = results;
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您的转换器支持实验代码(阶段0),则可以使用以下代码:

class RootView extends Component {
  cachedData = [];
  someFunction(results) {
    this.cachedData[this.state.searchString.length - 1] = results;
  }
}
Run Code Online (Sandbox Code Playgroud)