在axios调用react

时间:2019-05-14 18:58:55

标签: javascript reactjs axios

我将axios调用链接到了不同的API。当我在功能内进行console.logging状态时,我正在获取更新状态。但是,当我使用console.login的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;

2 个答案:

答案 0 :(得分:2)

您永远不要尝试直接在React中修改状态。所以这行

this.state.cities.push({ city: `${city.name}`, description })

不起作用。而是通过将函数传递到setState并修改该状态来访问先前的状态:

this.setState(prevState => ({
   cities: [...prevState.cities, { city: `${city.name}`, description }]
}))

答案 1 :(得分:1)

在React中,您应该设置状态,而不是尝试将值推入属于状态一部分的数组中

更改:

this.state.cities.push({ city: `${city.name}`, description })

类似于:

const {cities} = this.state;
cities.push({ city: `${city.name}`, description });
this.setState(cities);