具有动态索引的setState键不起作用-ReactJS

时间:2018-12-25 07:28:03

标签: reactjs

我正在尝试setStatefor循环内使用索引,如下所示:

for (var i = 0; i <= 9; i++) {
  this.setState({
    location_option[i]: resourceData.location_option+i,
    location_option[i]_type: resourceData.location_option+i+_type,
  });
}

这就是我获取资源数据的方式

    var resource_eng = { 
       location_option1: "Headquarters", 
       location_option1_type: "Office"
       ...
    }

然后我得到如下资源

var resourceDataObj = {}
resourceDataObj.en = resource_en.resource_eng;
resourceDataObj.ar = resource_ar.resource_ar;
var resourceData = new LocalizedStrings(resourceDataObj);
var resourceData = this.child.getResourceData();

我想setState并获得如下状态

this.state.location_option0
this.state.location_option0_type
this.state.location_option1
this.state.location_option1_type

以此类推...但是构建失败,并出现以下错误:

Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Step6.js: Unexpected token, expected "," (63:23)

  61 |     for (var i = 0; i <= this.state.index; i++) {
  62 |       this.setState({
> 63 |         location_option[i]: resourceData.location_option+i,

2 个答案:

答案 0 :(得分:2)

您用于生成动态密钥的语法不正确。您可以使用模板字符串生成类型的动态密钥。我假设您的resourceData看起来像这样。

const resourceData = {
   location_option1: "somedata",
   location_option1_type: "sometype",
}

for (var i = 0; i <= 9; i++) {
      this.setState({
        [`location_option${i}]: resourceData[`location_option${i}`],
        [`location_option${i}_type`]: resourceData[`location_option${i}_type`],
      });
    }

答案 1 :(得分:0)

始终最好将数组保留为状态变量,然后对其进行迭代以获取值

let location = [];
for (let i = 0; i <= 9; i++) {
  location[i] = {
    option: resourceData[`location_option${i}`],
    type: resourceData[`location_option${i}_type`]
   };
}
this.setState({ location }); // shorthand for this.setState({ location: location });

现在,您只需在任意位置使用this.state.location变量即可。