2

I would like to declare many variables into the state. How to use dynamic method to do that?

For example:

constructor(props) {
    super(props);

    this.state =
    {
     test1: this.props.navigation.state.params.rowData.test1,
     test2: this.props.navigation.state.params.rowData.test2,
      .........
     test50: this.props.navigation.state.params.rowData.test50
    }
}
Robert Hovhannisyan
  • 2,938
  • 6
  • 21
  • 43
Howard Lam
  • 41
  • 3

2 Answers2

3

You can use for loop for that. For example:

for(let i = 0; i < 50; i++){
  this.setState({ [i]: this.props.navigation.state.params.rowData.[i] })
}

If you want to do it exactly how in your example, you must push all your tests in the object, and in the setState just set this object.

Something like this:

var obj = {};
for(let i = 0; i < 50; i++){
  obj[test+i] = test+i;
}
this.setState({test: [ ...this.state.test, obj]});
Robert Hovhannisyan
  • 2,938
  • 6
  • 21
  • 43
0

Why not just spread them in?

this.state = { ...this.props.navigation.state.params.rowData }
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • what is the meaning of ... ? – Howard Lam Sep 20 '19 at 13:47
  • 1
    @HowardLam it's a "Object Spread" operator. The ES6 syntax for `Object.assign()` . For more information you can read this article: https://thecodebarbarian.com/object-assign-vs-object-spread.html – Robert Hovhannisyan Sep 20 '19 at 14:07
  • Thanks. it works now. but there is one more questions.....how can I use looping for set state petty+i?? any syntax i can use? this.setState({petty+i:text})} value={eval("this.state.petty"+i)} /> – Howard Lam Sep 20 '19 at 15:14
  • 1
    @HowardLam You keep using eval. As I said in a previous comment this is completely unnecessary by using bracket Boston for your property access. You may want to take a step back--there's a few things going here that make me think some tutorials on basic JS, React, and data structures will save you significant time and headaches. – Dave Newton Sep 20 '19 at 15:44