【问题标题】:React - get data with axiosReact - 使用 axios 获取数据
【发布时间】:2022-01-04 08:22:17
【问题描述】:

在我的基于类组件的 react 应用程序中,我的响应 API 来自几个 滞后 后的开放天气修复。 这是我的状态

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

我的想法是,当我的 componentDidMount, 从openWeather获取天气API并将其设置为状态

  componentDidMount() {
    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)

  }

但问题是当我的响应收到时,它面临一个延迟,导致数据跳到以前的数据和新的数据,直到它修复为止

【问题讨论】:

  • 我至少想显示加载文本,直到我的响应完全得到
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: reactjs api axios openweathermap react-class-based-component


【解决方案1】:

我不完全理解这个问题,但这个“滞后”是因为从外部来源获取内容的操作是异步的,需要时间来完成。

至于显示加载文本的第二个“部分”,您必须设置一个变量(最好是指示该组件的加载状态的状态)

例如。

 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 将在异步操作(从 weatherAPI 获取数据)以错误或成功结束时触发,此时停止加载。

然后你可以在组件渲染中使用this.state.loading来显示加载文本 例如。

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

【讨论】:

  • 我的主要问题是延迟,它会导致我的数据在几次跳转后加载,你是对的,我尝试从openWeather 获得回复以在我的页面上显示天气温度,但似乎需要时间来完成,所以我该如何处理这种滞后?
  • 我在底部的例子中写了..根据加载状态你可以显示你自己的加载动画而不是&lt;div&gt;loading...&lt;/div&gt;
猜你喜欢
  • 2020-08-21
  • 2018-01-31
  • 2019-08-26
  • 2020-07-20
  • 2020-06-19
  • 2021-07-27
  • 2020-12-05
  • 2021-02-08
  • 2021-12-05
相关资源
最近更新 更多