简体   繁体   English

状态在axios调用后未更新

[英]State not updating after axios call in react

I got chained axios call to different API's. 我将axios链接到不同的API。 When i console.logging state inside function, i am getting updated state. 当我在功能内进行console.logging状态时,我正在获取更新状态。 However, when i am console.logging in render() method i am not getting updated state. 但是,当我在console.logging中使用render()方法时,我没有得到更新状态。

Function is fired off after submit button is clicked, so the component is being re-rendered in my opinion. 单击提交按钮后,功能被关闭,因此我认为该组件正在重新呈现。

App.js 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;

You should never try to directly modify state in React. 您永远不要尝试直接在React中修改状态。 So this line 所以这条线

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

won't work. 将无法正常工作。 Instead, access the previous state by passing a function to setState and modify that: 相反,通过将一个函数传递给setState并修改该状态来访问先前的状态:

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

In React you should set state instead of trying to push values into an array that's is part of the state 在React中,您应该设置状态而不是尝试将值推入状态的一部分的数组中

change: 更改:

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

to something like: 像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM