reactjs - react:创建和使用动态变量
问题描述
我有一个列表/数组cities = ["Bangalore", "Delhi", "Hyderabad", "Mumbai", "Chennai"]
。我需要动态变量,如[city]Weather
,[city]Temperature
等。例如:我需要 BangaloreWeather、DelhiWeather、HyderabadWeather、MumbaiWeather、ChennaiWeather 和类似的温度。
我尝试使用 1) ${city}Weather
,但出现“复杂绑定模式需要初始化值”的错误,2)city+"Weather"
请帮助我解决问题。提前致谢
解决方案
使用 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
}
推荐阅读
- javascript - 使用 Ionic 3 从 Firebase 中删除数据
- c - 在不知道维度的情况下,在 C 中创建指向多维数组的指针
- python - 多处理:使用带有大字典的`pool.starmap`
- javascript - 在 promise.all 完成后执行操作?
- mongodb - 您如何按单位而不是小数截断或舍入数字?
- python - 在 django 中根据基于关系的键、值创建表单
- ios - 如何为分布式应用程序实现非对称加密,其中密钥都可以存储为字符串?
- c++ - 为什么 std::map::emplace 使用会泄漏内存?
- python - Pandas:将摘要信息添加到 groupby 框架中的新列
- python - Selenium IDE 可以工作,但 Python Selenium 不能:可能是 iFrame 问题