首页 > 解决方案 > react:创建和使用动态变量

问题描述

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

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

标签: reactjsvariablesreduxbabeljs

解决方案


使用 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
}

推荐阅读