[英]State not updating after axios call in react
我將axios鏈接到不同的API。 當我在功能內進行console.logging狀態時,我正在獲取更新狀態。 但是,當我在console.logging中使用render()方法時,我沒有得到更新狀態。
單擊提交按鈕后,功能被關閉,因此我認為該組件正在重新呈現。
App.js
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import CitySearchForm from './CitySearchForm/CitySearchForm';
import CityOutput from './CityOutput/CityOutput';
class App extends Component {
state = {
country: '',
error: false,
cities: []
}
getCities = (e) => {
e.preventDefault();
const countryName = e.target.elements.country.value.charAt(0).toUpperCase() + e.target.elements.country.value.slice(1);
const countryUrl = 'https://api.openaq.org/v1/countries';
const wikiUrl ='https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&explaintext&format=json&category=city&redirects&origin=*&titles=';
axios
.get(countryUrl)
.then( response => {
const country = response.data.results.find(el => el.name === countryName);
return axios.get(`https://api.openaq.org/v1/cities?country=${country.code}&order_by=count&sort=desc&limit=10`)
})
.then( response => {
const cities = response.data.results.map(record => {
return { name: record.city };
});
cities.forEach(city => {
axios
.get(wikiUrl + city.name)
.then( response => {
let id;
for (let key in response.data.query.pages) {
id = key;
}
const description = response.data.query.pages[id].extract;
this.state.cities.push({ city: `${city.name}`, description })
})
})
})
.catch(error => {
console.log('oopsie, something went wrong', error)
})
}
render () {
console.log(this.state.cities)
return (
<div className="App">
<CitySearchForm getCities={this.getCities} getInformation={this.getInformation}/>
{this.state.cities.forEach( item => {
item.map(({ city, description }) => (
<CityOutput
city={city}
description={description} />
))
})}
</div>
);
}
}
export default App;
您永遠不要嘗試直接在React中修改狀態。 所以這條線
this.state.cities.push({ city: `${city.name}`, description })
將無法正常工作。 相反,通過將一個函數傳遞給setState
並修改該狀態來訪問先前的狀態:
this.setState(prevState => ({
cities: [...prevState.cities, { city: `${city.name}`, description }]
}))
在React中,您應該設置狀態而不是嘗試將值推入狀態的一部分的數組中
更改:
this.state.cities.push({ city: `${city.name}`, description })
像這樣:
const {cities} = this.state;
cities.push({ city: `${city.name}`, description });
this.setState(cities);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.