如何在同一個渲染中處理多個 api 呼叫?
例子 :
我想從第一個 API 呼叫中獲取一些資訊,例如:
const getUserInfo = async () => {
const response = await axios
.get(`${API}/api/tenants/${app.tenant}/users/me`, axiosConfig)
.then((r) => {
return r.data;
})
.catch((e) => {
console.log("ERORR", e);
});
return response;
};
const USER_INFO_SETTER = async () => {
const fulldata = await getUserInfo();
setUsername(fulldata.username);
setDisplayname(fulldata.display_name);
setId(fulldata.id);
getAvatarId(fulldata.profile_image);
setFirstName(fulldata.first_name);
setLastName(fulldata.last_name);
};
useEffect(() => {
USER_INFO_SETTER();
}, [isFocused]);
我想立即將它用于此呼叫下的下一個 API CALL
例子 :
const GET_ACTIVE_PROFILE_PICTURE = async () => {
try {
const rez = await axios
.get(`${API}/api/documents/document/${user.avatar_id}`, axiosConfig)
.then((r) => {
return r.config.url;
})
.catch((e) => {
console.log("ERROR", e);
});
return rez;
} catch {
console.log("error");
}
};
const avatarSetted = async () => {
const avatarLink = await GET_ACTIVE_PROFILE_PICTURE();
setProfileImage(avatarLink);
};
useEffect(() => {
avatarSetted();
console.log("123");
}, []);
Soo 的問題是如何在下面的 api 呼叫中使用我在第一個 API 呼叫中獲得的資訊。因為沒有該資訊,例如 user.id_picture,我的第二個 api 呼叫將回傳 500。
謝謝您的幫助 :)
uj5u.com熱心網友回復:
首先,我會創建幾個像這樣的函式:
const getUserInfo = () => {
// This contains the axios request and returns the response.
};
const getActiveProfilePicture = () => {
// This contains the axios request and returns the response.
};
const fetchUserInfo = () => {
// This calls the getter and uses the response to update state.
};
const fetchActiveProfilePicture = () => {
// This calls the getter and uses the response to update state.
};
我還將介紹 2 個狀態變數,您可能已經有了這些,因此這一步可能是不必要的。
const [avatarId, setAvatarId] = useState(null);
const [profileImage, setProfileImage] = useState(null);
填寫您在上面添加的函式的邏輯。
const fetchUserInfo = useCallback(async () => {
const response = await getUserInfo();
// Perform all state updates.
setAvatarId(response.profile_image);
}, []);
const fetchActiveProfilePicture = useCallback(async () => {
const response = await getActiveProfilePicture();
// Perform all state updates.
setProfileImage(response);
}, []);
接下來,創建兩個useEffects:
- 當組件掛載時,呼叫
fetchUserInfo. - 當
avatarId已被檢索并最終設定為狀態時,呼叫fetchActiveProfilePicture。
useEffect(() => {
fetchUserInfo();
}, []);
useEffect(() => {
if(avatarId) {
fetchActiveProfilePicture();
}
}, [fetchActiveProfilePicture, name]);
這是帶有 PokeAPI 的 CodeSandbox 示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/359558.html
標籤:javascript 反应 反应原生 接口 还原
