我需要链接来自 Google Maps API 的一些 API 请求,并且我正在尝试使用 Axios 来完成它。
这是第一个请求,在 componentWillMount()
axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p1)
.then(response => this.setState({ p1Location: response.data })) }
这是第二个请求:
axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p2)
.then(response => this.setState({ p2Location: response.data }))
然后我们有第三个请求,它依赖于前两个请求的完成:
axios.get('https://maps.googleapis.com/maps/api/directions/json?origin=place_id:' + this.state.p1Location.results.place_id + '&destination=place_id:' + this.state.p2Location.results.place_id + '&key=' + 'API-KEY-HIDDEN')
.then(response => this.setState({ route: response.data }))
我怎样才能链接这三个调用,以便第三个发生在前两个之后?
原文由 Freddy 发布,翻译遵循 CC BY-SA 4.0 许可协议
首先,不确定您是否想在
componentWillMount
中执行此操作,最好将其放在componentDidMount
中,并且有一些默认状态会在完成这些请求后更新。其次,您想限制您编写的 setState 的数量,因为它们可能会导致额外的重新渲染,这是使用 async/await 的解决方案: