我有一個簡單函式的問題,我想呼叫一個 API,然后對回應做一些事情。基本上,我只想將我的反應組件狀態設定為我得到的回應,然后導航到另一個頁面問題是我的代碼在 API 呼叫完成之前執行了函式的另一部分,我最終在另一個頁面上未定義的 console.log
有我的功能:
const startNewGame = () => {
GameService.startGame()
.then((response) => {
setGame(response.data);
console.log(game);
navigate('intro');
})
.catch((e) => {
console.log(e);
});
};
我可以將導航包裝進去,if(!game !== undefined)但是我必須在一個按鈕上單擊兩次或更多次。
謝謝大家的幫助:)
uj5u.com熱心網友回復:
您可能同時做了幾件不正確的事情,因此要了解究竟是什么錯誤可能需要一些時間。執行以下步驟來除錯您的代碼:
- 讓每個
.then電話只做一件事(在其他情況下堅持這個原則)。您可以根據需要鏈接盡可能多的 .then。此外,您可以將資料從一個回傳.then到下一個,因此您的代碼可能如下所示:
GameService.startGame()
.then(response => response.data)
.then(data => {
setGame(data)
})
.then(() => {
console.log(game);
navigate('intro');
})
.catch((e) => {
console.log(e);
});
了解您的組件組成。你到底在哪里保存你的回復?它只是本地組件 useState 還是包裝應用程式的一些 Context Api 狀態?當您導航到“其他頁面”時,您的“當前頁面”狀態將對“其他頁面”不可用,除非您將資料保存在樹中的某個位置,而這兩個頁面都可以訪問該資料。
如需進一步參考,請記住 setGame 是異步的,因此您需要等待狀態更新以確保其已更新。
uj5u.com熱心網友回復:
試試這個:
const startNewGame = () => {
GameService.startGame()
.then((response) => {
setGame(response.data);
// game is not updated yet
// console.log(game); <- Remove this line
// navigate('intro'); <- Remove this line
})
.catch((e) => {
console.log(e);
});
};
useEffect(()=>{
if(game !== undefined){
navigate('intro')
}
}, [game])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/405283.html
標籤:
