React转换道具对象到数组然后setState [英] React convert props Objects into array then setState

查看:518
本文介绍了React转换道具对象到数组然后setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要转换此道具:

进入这个数组:

this.setState({
            locations: [
                { label: 'California', value: 'california' },
                { label: 'Nevada', value: 'nevada' },
            ]
});

最初我使用的是插件并想用我的道具替换它的默认值,但不能转换它。

originally i was using this plugin and wanted to replace its default values with my props but cant convert it.

推荐答案

取决于您的JavaScript风格和写作偏好

Depending on your flavor of JavaScript and preference of writing

利用 for .. in 操作员,带有缺点。
它将循环遍历所有可枚举属性,即使是原型中的属性。

Taking advantage of the for .. in operator, which comes with draw backs. It'll loop over all enumerable properties even the ones from the prototype.

var arr = [];
for (var key in myObject) {
  arr.push(myObject[key]);
}

或使用 Object.keys 方法

var arr2 = Object.keys(myObject).map(function (i) {
  return myObject[i];
});

或者最后,如果您正在运行Babel转换的应用程序, Object.values

or lastly, if you're running an Babel transpiled app, Object.values

var arr3 = Object.values(myObject);

这篇关于React转换道具对象到数组然后setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆