反应:创建和使用动态变量

时间:2018-07-16 07:20:16

标签: reactjs variables redux babel

我有一个列表/数组cities = ["Bangalore", "Delhi", "Hyderabad", "Mumbai", "Chennai"]。我需要[city]Weather[city]Temperature等动态变量。例如:我还需要BangaloreWeather,DelhiWeather,HyderabadWeather,MumbaiWeather,ChennaiWeather以及类似的温度指标。

我尝试使用 1)${city}Weather,但出现错误,因为“复杂的绑定模式需要初始化值”, 2)city+"Weather"     请帮助我解决问题。谢谢!

1 个答案:

答案 0 :(得分:0)

使用ES6,这可能有帮助?

const outcome =  ["Bangalore", "Delhi", "Hyderabad", "Mumbai", "Chennai"].reduce((accumulator, currentValue) => {
  accumulator[currentValue+"Weather"] = Math.random();
  return accumulator;
},{});

OUTPUT: 
{
  "BangaloreWeather": 0.7831037919683015,
  "DelhiWeather": 0.03695139822965743,
  "HyderabadWeather": 0.10986926586742629,
  "MumbaiWeather": 0.676334213130112,
  "ChennaiWeather": 0.9095092973413457
}