我需要从Google Maps API链接一些API请求,我正在try 使用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 }))

我如何将这三个电话连接起来,使第三个电话在前两个电话之后发生?

推荐答案

首先,如果你不确定你是否想在你的componentWillMount中这样做,最好在componentDidMount中有它,并且有一些默认状态,一旦完成这些请求就会更新.其次,要限制写入的setstate的数量,因为它们可能会导致额外的重新呈现,下面是一个使用async/await的解决方案:

async componentDidMount() {

  // Make first two requests
  const [firstResponse, secondResponse] = await Promise.all([
    axios.get(`https://maps.googleapis.com/maps/api/geocode/json?&address=${this.props.p1}`),
    axios.get(`https://maps.googleapis.com/maps/api/geocode/json?&address=${this.props.p2}`)
  ]);

  // Make third request using responses from the first two
  const thirdResponse = await axios.get('https://maps.googleapis.com/maps/api/directions/json?origin=place_id:' + firstResponse.data.results.place_id + '&destination=place_id:' + secondResponse.data.results.place_id + '&key=' + 'API-KEY-HIDDEN');

  // Update state once with all 3 responses
  this.setState({
    p1Location: firstResponse.data,
    p2Location: secondResponse.data,
    route: thirdResponse.data,
  });

}

Reactjs相关问答推荐

无法在列表中看到文本

在一个地方调用函数会影响其他地方调用该函数

如何将Redux工具包添加到expo (SDK 50)项目?

有没有办法让两个状态在两次精准渲染中更新?

将对象添加到集合中的数组时的no_id字段

UseEffect和useSelector的奇怪问题导致无限循环

有没有办法将在服务器端全局获取的一些数据传递到Next&>13应用程序目录中的客户端组件?

面对动画警告:未指定`useNativeDriver`.这是必需的选项,并且必须在REACT本机中显式设置为`true`或`False`

如何使用皮金贴图在Reactjs中制作 map 上的点之间的线的动画?

如何在与AntD的react 中限制文件上传和显示消息?

如何解决Reaction中遗留的上下文API错误?

为什么React UseEffect挂钩在页面重新加载时运行

使用以Jest 的方式返回 Promise 的方法来模拟可构造的 API 类时出现问题

Redux 工具包不更新状态

如何在 React.js 中提取 PDF 的内容?

DatePicker MUI 如何在日历左侧显示清除文本

当用户输入相同信息时如何禁用更新

在 Formik 表单中访问子组件的值

使用 react-router-dom 时弹出空白页面

如果查询不存在,如何返回所有产品?