【问题标题】:Using axios response data in another axios request在另一个 axios 请求中使用 axios 响应数据
【发布时间】:2021-01-10 12:17:41
【问题描述】:

我正在使用 axios 来获取信息,并且我需要在不同 axios 响应的另一个处理程序中获取该信息。我似乎无法在第二个响应处理中使用第一个响应中加载的数据。

例如:

const [firstData, setFirstData] = useState({});
const [secondData, setSecondData] = useState({});

await axios.get("url/firstRoute").then((response) => {
    setFirstData(response.data);
}).then(async () => {
    await axios.get("url/secondRoute").then((response) => {
        setSecondData(firstData); // firstData is still an empty Object here for some reason
    })
});

当我在第二个请求中时,如何确保 firstData 不为空? 我还尝试对 firstData 使用 useEffect 挂钩,并在其中调用第二个 axios 请求,但我仍然得到 firstData 为空的相同结果。 (假设两个请求都返回数据)

【问题讨论】:

    标签: reactjs axios state


    【解决方案1】:

    您可以像这样从第一个 .then 返回值:

    await axios
      .get('url/firstRoute')
      .then((response) => {
        setFirstData(response.data);
        return response.data;
      })
      .then(async (firstData) => {
        await axios.get('url/secondRoute').then((response) => {
          setSecondData(firstData); // firstData is still an empty Object here for some reason
        });
      });
    

    在您的代码中,您正在设置状态,但它没有在您的 then 子句之前完成。

    【讨论】:

      猜你喜欢
      • 2022-11-29
      • 1970-01-01
      • 2020-10-22
      • 2019-10-30
      • 2020-03-23
      • 2019-06-20
      • 1970-01-01
      • 2020-07-21
      • 2021-08-14
      相关资源
      最近更新 更多