对于从fetch调用中过滤出的结果执行map函数时,我遇到了问题,到目前为止,我已经花了7个小时没有用。
我正在尝试根据所选国家/地区动态呈现可用城市的列表。
第一个用户选择国家/地区,然后获取功能开始从JSON文件中获取所有城市的列表,这些城市通过“ element ==== element.country”条件进行了过滤。
由于某种原因,我从fetchCityList函数获得的所有信息'无法读取未定义的属性'map',并且页面崩溃,即使当我用console.log记录结果时,它们也会返回一个漂亮的对象数组。
奇怪的是,filterCitiesByCountry函数返回的结果与fetchCityList完全相同,但是由于某些原因,filterCitiesByCountry的结果被传递到映射函数中,是否fetchCityList会使站点崩溃也很好。
我还认为可能是初始渲染崩溃了,因为获取需要花费一些时间,并且在渲染开始时fetchCityList返回null,但随后我添加了this.state.citiesFetched,仅在成功获取城市后才进行更改,因此我一无所知从现在开始要去哪里。
// DOM rendering
<select className='custom-select' onChange={this.handleCitySelect} placeholder='City...' required>
<option value='' data-index='City...'> </option>
{ this.state.citiesFetched && this.fetchCityList(this.state.country).map(({name, key}) =>
<option value={name} key={key}> {name} </option>
)}
</select>
// Faulty function resulting in " Cannot read property 'map' of undefined".
// BTW: console.log(country) shows currently selected country from this.state.country so that part is fine.
// BTW2: console.log(res.filter(res => res.country === country)) also shows an array of filtered objects.
fetchCityList = (country) => {
fetch("/weatherly_app/json/citiesList.json")
.then( res => res.json())
.then( res => {
return res.filter(res => res.country === country)
})
.then( res =>
this.setState ({
citiesFetched: true
})
)
};
// Function for setting this.state.city which is then used as parameter for fetchCityList function
handleCountrySelect = (e) => {
this.setState({
country: e.target.value,
country_desc: e.currentTarget['data-desc'],
city: '',
showGetWeatherBtn: false
});
};
// This works perfectly but I was using a huge JSON file imported directly to the component which (I assume) would devastate user loading times
filterCitiesByCountry = (country) => {
return citiesJSON.filter ( city => city.country === country)
};
handleCitySelect = (e) => {
this.setState ({
city: e.target.value
});
};