【发布时间】:2026-02-01 03:30:01
【问题描述】:
我刚刚开始了一个简单的天气应用项目来训练 React 和数据获取。
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
class App extends Component {
constructor(props) {
super(props);
this.state = {
city: "",
id: 0
}
this.choseCity = this.choseCity.bind(this);
this.cityName = this.cityName.bind(this);
this.cityInfo = this.cityInfo.bind(this);
}
chooseCity(e) {
console.log(e.target.value)
this.setState({
city: e.target.value
});
}
cityName() {
axios.get(`https://www.metaweather.com/api/location/search/?query=${this.state.city}`)
.then(res => res.data)
.then(data => this.setState({
city: data[0].title,
id: data[0].woeid}))
}
cityInfo() {
axios.get(`https://www.metaweather.com/api/location/${this.state.id}/`)
.then(res => console.log(res.data))
}
render() {
return (
<div className="App">
<input type="text" placeholder="Enter city name" value={this.state.city} onChange={this.chooseCity}/>
<button onClick={this.cityName}>Name</button>
<button onClick={this.cityInfo}>Info</button>
</div>
);
}
}
export default App;
所以,我有 2 个函数(cityName 和 cityInfo),我可以在 2 个不同的 onClick 事件上执行它们。他们似乎都独立工作。
cityName() 请求存储在我所在州的数据。
cityInfo() 在请求的 url 中使用此状态来获取更多信息。
我正在尝试链接它们以便能够在一次调用中检索所有数据,但由于它们都是异步的,所以我的第二个请求在第一个请求的数据存储在我的状态之前开始,并且有没有办法在 api 中我可以直接在一个请求中获取我需要的信息。
我已经尝试了一些方法,比如将它们分组到一个函数中,但到目前为止还没有定论。
解决方案:@elsyr
这是如何使用请求之间的数据链接到一个函数:
cityInfo() {
axios.get(`https://www.metaweather.com/api/location/search/?query=${this.state.city}`)
.then(res => res.data)
.then(data => {
axios.get('https://www.metaweather.com/api/location/' + data[0].woeid)
.then(res => res.data)
.then (data => this.setState({
info: data
}))
});
}
【问题讨论】:
-
尝试了异步/等待,在发出第二个请求之前,它似乎仍然没有在我的状态下存储数据:/
标签: javascript reactjs httprequest axios