簡體   English   中英

React - 使用 axios 獲取數據

[英]React - get data with axios

在我的基於 class 組件的反應應用程序中,我的響應API在幾個滯后后從開放的天氣修復中得到。 這是我的 state

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

我的想法是,當我的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)

我想在城市發生變化時更新數據,在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)

  }

但問題是,當我的響應收到時,它面臨一個滯后,導致數據多次跳轉到以前的數據和新的數據,直到它修復

我不完全理解這個問題,但是這個“滯后”是因為從外部源獲取某些東西的操作是異步的,需要時間來完成。

至於顯示加載文本的第二個“部分”,您必須設置一個變量(最好在 state 中,它表示該組件的加載 state)

例如。

 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獲取數據)以錯誤或成功完成(即停止加載的時間)完成,就會觸發.finnally。

然后您可以在組件渲染中使用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