gpt4 book ai didi

reactjs - 在另一个 axios 请求中使用 axios 响应数据

转载 作者:行者123 更新时间:2023-12-04 15:17:32 27 4
gpt4 key购买 nike

我正在使用 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 Hook ,并在其中调用第二个 axios 请求,但我仍然得到 firstData 为空的相同结果。(假设两个请求都返回数据)

最佳答案

您可以像这样从第一个 .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 子句之前完成。

关于reactjs - 在另一个 axios 请求中使用 axios 响应数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64042481/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com