简体   繁体   English

React - 使用 axios 获取数据

[英]React - get data with axios

In my react app that is based on class components, My response API got from open weather fixes after several lags .在我的基于 class 组件的反应应用程序中,我的响应API在几个滞后后从开放的天气修复中得到。 this is my state这是我的 state

class Weather extends Component {
  constructor(props) {
    super(props);
    this.state = {
      weatherData: undefined,
      weatherDescription: undefined,
    };
  }

My thinking was that when my componentDidMount , weather API getting from openWeather and set it in state我的想法是,当我的componentDidMount ,天气 API 从openWeather获取并将其设置在 state

  componentDidUpdate() {
    axios
      .get(
        `http://api.openweathermap.org/data/2.5/weather?id=someCityId&units=metric&appid=myApiKey`
      )
      .then((response) => {
        if (response.request.status === 200) {
            this.setState({
              weatherData: response.data.main.temp,
              weatherDescription: response.data.weather[0].description,
              weatherTextDisplay: this.state.airConditionsText.filter((item)=>{
                return item["id"] === response.data.weather[0].id
              })
            });
        }else{throw Error('No internet')}
      })
      .catch(error => Error.message)

and I want to update data when the city is changing, in componentDidUpdate the data get again from the openWeather我想在城市发生变化时更新数据,在componentDidUpdate中再次从openWeather获取数据

componentDidUpdate() {
    axios
      .get(
        `http://api.openweathermap.org/data/2.5/weather?id=someCityId&units=metric&appid=myApiKey`
      )
      .then((response) => {
        if (response.request.status === 200) {
            this.setState({
              weatherData: response.data.main.temp,
              weatherDescription: response.data.weather[0].description,
              weatherTextDisplay: this.state.airConditionsText.filter((item)=>{
                return item["id"] === response.data.weather[0].id
              })
            });
        }else{throw Error('No internet')}
      })
      .catch(error => Error.message)

  }

But the problem is that when my response receives, it faces a lag that causes data jumps several times to previous data and new data until it fixes但问题是,当我的响应收到时,它面临一个滞后,导致数据多次跳转到以前的数据和新的数据,直到它修复

I do not completely understand the question, but this 'lags' because the action of fetching something from an external source is async and needs time to complete.我不完全理解这个问题,但是这个“滞后”是因为从外部源获取某些东西的操作是异步的,需要时间来完成。

As for the second 'part' of displaying the loading text you have to set a variable (preferably in state which indicates the loading state of this component)至于显示加载文本的第二个“部分”,您必须设置一个变量(最好在 state 中,它表示该组件的加载 state)

eg.例如。

 constructor(props) {
    super(props);
    this.state = {
       loading: false,
       airConditionsText: null,
       // Other stuff you have in state
    };
  }

  componentDidUpdate() {
    this.setState({loading: true}) // Start of loading
    axios
      .get(
        `http://api.openweathermap.org/data/2.5/weather?id=${this.state.inputId}&units=metric&appid=myApiKey`
      )
      .then((response) => {
        if (response.request.status === 200) {
            this.setState({
              weatherData: response.data.main.temp,
              weatherDescription: response.data.weather[0].description,
              weatherTextDisplay: this.state.airConditionsText.filter((item)=>{
                return item["id"] === response.data.weather[0].id
              })
            });
        }else{throw Error('No internet')}
      })
      .catch(error => Error.message)
      .finally(() => this.setState({loading: false})) // End of loading

.finnally is being trigger once the async operation (fetching the data from weatherAPI) finishes with either error or success which is the time to stop loading.一旦异步操作(从.finnally获取数据)以错误或成功完成(即停止加载的时间)完成,就会触发.finnally。

Then you can use this.state.loading in component render to show loading text eg.然后您可以在组件渲染中使用this.state.loading来显示加载文本,例如。

  render() {
    return (
        <div>
          {this.state.loading 
            ? <div> Loading... </div> 
            : <div>{this.state.airConditionsText}</div> // other stuff you want to display
          } 
        </div>
    );
  }

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

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