我正在用Ionic React開發一個應用程式,它向一個API執行一些HTTP請求。問題是我需要將請求的回應存盤在一個本地存盤中,以便在任何地方都可以訪問。我目前使用的方法是@ionic/storage:
let body = {
username: 用戶名。
password: password
};
sendRequest('POST', '/login', "userValid", body) 。
let response = await get("userValid") 。
if (response.success) {
window.location.href = "/main_tabs"/span>。
} else if (! response.success) {
alert("Incorrect password") 。
}
import { set } from ' ./storage';
//處理所有的API請求。
export function sendRequest(type: 'GET' | 'POST', route: string, storageKey: string, body?: any) {
let request = new XMLHttpRequest() 。
let payload = JSON.stringify(body)。
let url = `http://localhost:8001${route}`;
request.open(type, url)。
request.send(payload)。
request.onreadystatechange = () => {
if (request.ready === 4 && storageKey) {
set(storageKey, request.response) 。
}
}
問題是,當我得到userValid鍵時,回應還沒有回來,所以即使等待也會回傳未定義。正因為如此,我不得不每次都發送一個相同的請求,以便讓Ionic讀取正確的值,這實際上是第一個請求的回應。除了在每次執行請求時設定超時外,還有什么正確的方法嗎?
uj5u.com熱心網友回復:
你正在檢查設定之前的存盤結果。這是因為你的sendRequest方法正在呼叫一個異步的XMLHttpRequest請求,而你在sendRequest方法完成之前就檢查了存盤。這可以通過使sendRequest成為異步的,并對你的代碼進行一些重組來解決。
我建議您轉而尋找 ionic react 使用鉤子或 API 庫的示例 - 如 fetch 或 Axios。這將使你的生活變得更加輕松,你應該能找到很多的例子和檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/330246.html
標籤:
