【问题标题】:passing data back to calling function of async request将数据传回异步请求的调用函数
【发布时间】:2018-05-22 12:05:49
【问题描述】:

我在returning data from async requests 上阅读了此答案,但我仍然难以确定如何在我的应用程序中应用这些答案。

在下面的代码中,我试图访问 getWeather 异步请求的返回结果,并在 getWeather 下面的 return 语句后面的 jsx 中使用该数据。

我注意到上一个 OP 问题的答案说要在回调函数中处理结果,但我不知道如何通过 getWeather 调用将其传递回链。

我的问题 - 我如何将这些数据传回并在 FiveDayWeather 函数中访问它?

const URL = `http://api.openweathermap.org/data/2.5/forecast?zip=94040&appid=${OPEN_WEATHER_KEY}`

const FiveDayWeather = () => {
  let days = getWeather()

  return(
    <div className="five-day-weather">
      <div className="day-of-week-item">
        <div className="day">Hi Again</div>
        <div className="image-indicator"></div>
        <div className="temp"></div>
      </div>
    </div>
  )
}

function getWeather() {
  axios.get(URL)
    .then(function(response) {
      handleData(response)
    })
}

function handleData(response) {
  return response
}

【问题讨论】:

    标签: javascript reactjs asynchronous promise


    【解决方案1】:

    您应该在componentDidMount 方法中进行API 调用,并将结果设置在组件的state 中。然后在你的渲染方法中,你需要使用state

    constructor(props) {
        super(props);
        this.state = {
          error: null,
          isLoaded: false,
          days: []
        };
    
      }
    
    getWeather() {
      axios.get(URL)
        .then(response => {
           this.setState({
               isLoaded: true,
               days: response //Set the right value here from response
           });
        }).catch( error => {
           this.setState({
               isLoaded: true,
               error
           }); 
        });
     }
    
    render() {
        const { error, isLoaded, days } = this.state;
        if (error) {
          return <div>Error: {error.message}</div>;
        } else if (!isLoaded) {
          return <div>Loading...</div>;
        } else {
          return (
            // your template to show the data goes here
          );
        }
      }
    

    有关 AJAX here,请参阅 ReactJS 文档。

    【讨论】:

    • 这行不通。 axios.get(URL).then()里面的函数没有绑定到组件,所以不能访问this.setState()
    • 更新为使用箭头函数
    【解决方案2】:

    你的函数getWeather() 没有返回任何东西,handleData() 没有按照你的想法做。

    您应该尝试使用async 函数,而不是大量返回。 axios 异步工作。因此,await 将等到从 axios 中检索到数据,然后将其返回。试试这样:

    async function getWeather() {
     return await axios.get(URL)
    }
    

    【讨论】:

    • 这也不行,它会返回一个空对象!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2021-08-10
    • 2015-12-01
    相关资源
    最近更新 更多