[英]Get Promise Value (axios inside Axios) and set to Hook
我有 2 個 axios 函數,一個是返回貨幣名稱列表,另一個是獲取所述貨幣的價值。 我需要獲得相應的貨幣價值。
[currencies, setCurrencies] = useState([]);
getCurrencyNames = () =>
axios({
method: `get`,
url: `${url}/getCurrencies`
}).then(r =>
setCurrencies(r.data.map(currency => {
return {
name: currency,
value: getCurrencyValue(currency)
}
}))
);
getCurrencyValue = async (currency) => {
const data = await axios({
method: `get`,
url: `${url}/getValue/?from=PHP&to=${currency}`
}).then(r => r.data)
return data;
}
應該返回的是用如下對象填充的貨幣掛鈎:
{
name: "USD",
value: 0.020
}
但對象返回如下:
{
name: "USD",
value: Promise
}
我還嘗試將鈎子設置為 getCurrencyValue ,如下所示:
getCurrencyValue = async (currency) => {
axios({
method: `get`,
url: `${url}/getValue/?from=PHP&to=${currency}`
}).then(r =>
setCurrencies([
...currencies,
name: currency,
value: r.data
])
)
}
但發生的情況是只有最后一個設置在鈎子內
它返回 promise 是正常的,您必須通過在調用之前放置 await 來解決它,並使 map function 異步:
getCurrencyNames = () =>
axios({
method: `get`,
url: `${url}/getCurrencies`
}).then(r =>
setCurrencies(r.data.map(async currency => {
return {
name: currency,
value: await getCurrencyValue(currency)
}
}))
);
import { useEffect, useState } from "react";
import axios from "axios";
function App() {
const [currencies, setCurrencies] = useState([]);
async function getCurrencyValue(post) {
const data = await axios({
method: `get`,
url: `https://jsonplaceholder.typicode.com/users`
}).then((r) => ({
post,
user: r.data
}));
return data;
}
function getCurrencyNames() {
return axios({
method: `get`,
url: `https://jsonplaceholder.typicode.com/posts`
}).then((r) => {
const res = Promise.all(
r.data.map(async (currency) => {
return {
name: currency,
value: await getCurrencyValue(currency)
};
})
);
return res;
});
}
useEffect(() => {
(async function () {
const data = await getCurrencyNames();
console.log(data);
console.log("fetched in useEffect");
setCurrencies(data);
})();
}, []);
return <></>;
}
export default App;
這是鏈接https://codesandbox.io/s/condescending-germain-8ie8j?file=/src/App.js
Note: See in the console
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.