You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何先请求API存储数据,再用该存储值发起第二次API请求

问题根因

React 中 setState 是异步批量更新的,并且你当前的 useEffect 依赖项是空数组,effect 内部形成闭包,持有的永远是首次渲染时的 destination 快照(初始值为空字符串)。即使 fetchTrackingData 里调用了 setDestination 更新状态,新的状态值也无法进入本次闭包,因此你在 finally 中拿到的永远是初始值,读取 coordinates 自然为 undefined。

解决方案

方案1:直接复用接口返回值(最推荐)

不需要依赖 state 更新,直接让第一个接口请求把需要的数据返回,拿到后直接传给第二个请求即可,同时正常存状态不影响后续渲染使用:
首先调整 fetchTrackingData,把获取到的目的地数据返回:

const fetchTrackingData = async () => {
  const res = await 调用你的跟踪数据接口
  const destinationData = res.data.destination
  setDestination(destinationData) // 正常存状态供渲染用
  return destinationData // 直接返回数据给调用方
}

然后改写 useEffect 用 async/await 做串行请求,逻辑更清晰:

useEffect(() => {
  const fetchData = async () => {
    setLoading(true)
    try {
      const destination = await fetchTrackingData()
      // 直接用返回的 destination 数据,不需要等状态更新
      console.log("Destination", destination.coordinates)
      await fetchDriverLocation(destination)
    } catch (err) {
      // 按需处理请求错误
      console.error('请求失败', err)
    } finally {
      setLoading(false)
    }
  }
  fetchData()
}, [])

方案2:监听状态变化触发第二个请求

如果你的业务逻辑确实需要等 destination 状态更新完成后再执行后续操作,可以拆分两个 useEffect,第二个 useEffect 监听 destination 变化触发:

// 第一个effect仅负责拉取第一份数据并存状态
useEffect(() => {
  fetchTrackingData()
}, [])

// 第二个effect监听destination,有有效值时再触发第二个请求
useEffect(() => {
  // 加判断避免初始空值时执行
  if (!destination?.coordinates) return
  const getDriverLocation = async () => {
    setLoading(true)
    try {
      console.log("Destination", destination.coordinates)
      await fetchDriverLocation()
    } finally {
      setLoading(false)
    }
  }
  getDriverLocation()
}, [destination])

内容的提问来源于stack exchange,提问作者incredible123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 02:18:02