为AJAX请求创建可重用函数

为AJAX请求创建可重用函数,ajax,reactjs,Ajax,Reactjs,我正在构建一个天气应用程序,并希望创建一个可重用的函数来生成AJAX请求,但我不知道如何使其工作。我的代码比文字更能解释我想要什么。如何使此功能正常工作 fetchWeather(reqCity) { var city = reqCity var searchText = ...a lot of stuff var results axios.get(`https://query.yahooapis.com/v1/public/yql?q=${searchText}&format=js

我正在构建一个天气应用程序,并希望创建一个可重用的函数来生成AJAX请求,但我不知道如何使其工作。我的代码比文字更能解释我想要什么。如何使此功能正常工作

fetchWeather(reqCity) {
var city = reqCity
var searchText = ...a lot of stuff
var results

axios.get(`https://query.yahooapis.com/v1/public/yql?q=${searchText}&format=json`)
.then(response => results = response.data.query.results.channel.item.condition)

return results //doesn't work because of asynchronicity
}

componentDidMount() {
var weatherInMoscow = this.fetchWeather('Moscow')
this.setState({
  moscow: weatherInMoscow 
})
}

您可以使用多种方法来实现这一点。最简单的方法之一是传递
回调
函数,并在
回调
(cb)中执行所需的操作

在您调用的地方,发送与此类似的回调,并在其中执行所需的操作

componentDidMount() {
 var weatherInMoscow = this.fetchWeather('Moscow', (data) => {
   this.setState({
    moscow: data 
   })
 })
} 
注意:此代码不显示如何处理错误。如果有错误,您需要在
cb
(回调)函数中添加逻辑来处理错误

componentDidMount() {
 var weatherInMoscow = this.fetchWeather('Moscow', (data) => {
   this.setState({
    moscow: data 
   })
 })
}