简体   繁体   中英

setState key with dynamic index not working - ReactJS

I'm trying to setState using index inside for loop like the following:

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

This is how i'm getting the resource data

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

then i get the resource like the following

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

I want to setState and get the state as following

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

and so on...but the build is failing with the following error:

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,

Your syntax for generating dynamic key is not correct. You can use template string to generate dynamic key for type. I am assuming your resourceData looks something like.

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`],
      });
    }

its always better to keep an array as state variable and then iterate over it to get the value

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

Now, you can just use this.state.location variable anywhere you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM