![](/img/trans.png)
[英]react - Infiinite loop when sending axios request (useState problem?)
[英]Weird React problem with axios and useState
我的問題是關於嵌套的 axios 請求。 代碼非常簡單,首先是 axios.get 我正在獲取第一部分數據,然后使用給定的響應我試圖從第二個端點獲取數據。 (下面的代碼)
const getData = async () => {
let returnSecoundValue = {}
try {
const response = await axios.get("http://127.0.0.1:8000/firstEndpoint/", {
auth: {
username: "x",
password: "y",
},
});
// console.log(response.data) <--- WORKS;
response.data.forEach(async element => {
const secoundData = await axios.get(`http://127.0.0.1:8000/secoundEndpoint/${element.id}/`, {
auth: {
username: "x",
password: "y",
},
});
returnSecoundValue[secoundData.data.id] = secoundData.data
});
console.log(returnSecoundValue) <--- WORKS;
setMyState({firstEnd: response.data, secoundEnd: empoRet})
} catch (err) {
console.error(err);
}
如上例所示,當我完成獲取第二個數據時,我將其作為 object 保存在我的 state 中。 object 的第一個元素是對象數組,第二個元素是 object(用作磁盤)。
到目前為止一切都很好,當我嘗試 console.log 它時,它完美地顯示了我想要的。 當我試圖從第二個元素中獲取確切的數據時,問題就開始了。
使用我獲取的數據,我正在嘗試做這樣的事情:
myState.firstEnd.map((element) => {
try{
console.log(myState); (Works - log all values)
console.log(myState.secoundEnd); (Works - log all values of secoundEnd)
console.log(myState.secoundEnd[2]); (Return undefind)
<Component
key={element.id}
isActive={element.active}
title={element.title}
我試圖用幾種方法做到這一點,但每次我都得到相同的結果。 是安裝有問題還是有其他問題?
感謝評論,我發現了問題所在。 這是解決方案:
const secoundValue = response.data.map(async element => {
await axios.get(`http://127.0.0.1:8000/secoundEndpoint/${element.id}/`,
{
auth: {
username: "x",
password: "y",
},
});
});
Promise.all(secoundValue).then((res) => {
res.map((e)=>{
secoundEnd[e.data.id] = e.data
})
setMyState({ ads: resp.data, emp: empoRet });
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.