【发布时间】:2019-11-06 11:11:36
【问题描述】:
我创建了带有反应的基本天气应用程序,我想将所有 json 文件推送状态,但我不能这样做。
import React, {Component} from 'react';
import './App.css';
import CityList from './CityList';
// this is an array that just has id, city_name and country property
import {cityName} from './Resorces';
class App extends Component {
constructor (){
super()
this.state = {
cities:{},
}
}
render() {
const {cities} = this.state;
console.log('cities state', cities);
return (
<div className='tc'>
<h1 className='f1 pa3 ma2'> World Weather</h1><hr/>
<CityList cities={cities}/>
</div>
);
}
componentDidMount(){
const citySource = cityName.map((city) => {
return fetch(https://api.weatherbit.io/v2.0/current?city=${city.name}&country=${city.country}&key=86e622607fbe4c2cb9f7f71889a4d48d)
}).then(response => response.json())
.then( data => {this.setState({cities : data})});
console.log('citySource', citySource);
}
}
export default App;
上面的这段代码没有访问 Resorces.js 中的 cityName 数组,也没有执行 map() 循环,因此没有将 json 文件推送到 STATE 中的对象的城市
我该怎么做?
下面是cityName数组
export const cityName = [
{
id: 1,
name: "New York City",
country: "US",
},
{
id: 2,
name: "Vienna",
country: "AT",
},
{
id: 3,
name: "Istanbul",
country: "TR",
},
{
id: 4,
name: "London",
country: "GB",
},
{
id: 5,
name: "Ankara",
country: "TR",
},
{
id: 6,
name: "Paris",
country: "FR",
},
{
id: 7,
name: "Madrid",
country: "ES",
},
{
id: 8,
name: "Amsterdam",
country: "NL",
},
{
id: 9,
name: "Belgrade",
country: "RS",
},
{
id: 10,
name: "Munich",
country: "DE",
},
{
id: 11,
name: "Berlin",
country: "DE",
},
{
id: 12,
name: "Chicago",
country: "US",
},
{
id: 13,
name: "Brussels",
country: "BE",
},
{
id: 14,
name: "Rome",
country: "IT",
},
{
id: 15,
name: "Washington",
country: "US",
}
];
【问题讨论】:
-
能否在问题中添加cityName示例数据
-
如果它不是一个数组,所以 map 不起作用,array.map 是您可以在 mdn developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 上阅读更多信息的方法
-
@DILEEPTHOMAS 我现在肯定会做
-
找出了问题并发布了答案检查,让我知道快乐的编码 :) 并欢迎使用 stackoverflow :)