javascript React.js setState() 带有用于循环内键的变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34194207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:22:05  来源:igfitidea点击:

React.js setState() with variable for key inside loop?

javascriptreactjs

提问by narwic

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

有没有办法使用字符串变量的值作为 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.

React 会抛出上述语法错误,将 arr[i] 设置为变量最终会使用该变量的名称设置新状态。

回答by Dan Prince

You can create the object before calling setState.

您可以在调用之前创建对象setState

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

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

或者,如果您使用的是 ES6,则可以使用计算属性

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

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

但是这段代码会调用setState多次,只调用一次会更有效率。构建更新的状态对象,然后应用它。

var newState = {};

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

this.setState(newState);