Reputation: 41
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
}
}
Upvotes: 2
Views: 233
Reputation: 3341
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]});
Upvotes: 3
Reputation: 160271
Why not just spread them in?
this.state = { ...this.props.navigation.state.params.rowData }
Upvotes: 0