最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React.js setState() with variable for key inside loop? - Stack Overflow

programmeradmin0浏览0评论

Is there a way to use a string variable's value as the 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 arr[i] to a variable ends up setting a new state with that variable's name.

Is there a way to use a string variable's value as the 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 arr[i] to a variable ends up setting a new state with that variable's name.

Share Improve this question asked Dec 10, 2015 at 5:17 cy23cy23 1,2411 gold badge10 silver badges8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 22

You can create the object before calling setState.

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

Alternatively if you are using ES6, you could make use of a computed property.

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

However this code will call setState multiple times, it's more efficient to only call it once. Build the updated state object, then apply it.

var newState = {};

for(var i in arr) {
  newState[i] = number;
}

this.setState(newState);
发布评论

评论列表(0)

  1. 暂无评论