React.js setState () with variable for inner loop?

Is there a way to use the value of a string variable as a key for setState ()?

getInitialState: function () { return { foo: '', bar: '' } } someOtherHandler: function() { var arr = ['foo', 'bar']; var _this = this; var number = Math.random(); for (var i in arr) { _this.setState({ arr[i]: number }); } } 

React throws a syntax error with the above, and setting the arr [i] variable ends with setting a new state with this variable name.

+7
javascript reactjs
source share
1 answer

You can create an object before calling setState .

 var newState = {}; newState[i] = number; _this.setState(newState); 

Alternatively, if you are using ES6, you can use the computed property .

 _this.setState({ [i]: number }); 

However, this code will call setState several times, it is more efficient to call it only once. Create an updated state object, then apply it.

 var newState = {}; for(var i in arr) { newState[i] = number; } this.setState(newState); 
+14
source share

All Articles