我有 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
])
)
}
但發生的情況是只有最后一個設定在鉤子內
uj5u.com熱心網友回復:
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
uj5u.com熱心網友回復:
它回傳一個promise是正常的,您必須通過在呼叫之前放置await來解決它并使map函式異步:
getCurrencyNames = () =>
axios({
method: `get`,
url: `${url}/getCurrencies`
}).then(r =>
setCurrencies(r.data.map(async currency => {
return {
name: currency,
value: await getCurrencyValue(currency)
}
}))
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/363938.html
標籤:javascript 反应 公理
上一篇:打字稿中的未知資料型別
