为什么我在一个异步函数的中间有一个包含汇率数据的数组,而在它的外部有一个空数组?

bxgwgixi  于 2022-10-21  发布在  iOS
关注(0)|答案(1)|浏览(186)

我是编程新手,5天内我都解决不了这个问题。
我正在尝试从API中获取1到50000之间的特定货币的汇率。我设法在getCurrenciesValues​​异步函数的中间获得了正确的货币汇率,但在函数外部我得到了一个空数组。我已经尝试以不同的方式将数据从一个异步函数传输到该函数外部的空数组。使用了for循环,尝试使用Async/Wait,也使用**.Then().ush将数据发送到Async函数外部的数组。有时,在异步函数外部的控制台会向我显示一个包含数据的数组,但在使用JSON.stringify**时,它会指出该数组实际上是空的。我的代码如下所示

  1. const defaultData = [
  2. { value: 1 }, { value: 5 }, { value: 10 },
  3. { value: 25 }, { value: 50 }, { value: 100 },
  4. { value: 500 }, { value: 1000 }, { value: 5000 },
  5. { value: 10000 }, { value: 50000 }];
  6. function CurrencyTable({ choiceFrom, choiceTo, labelFrom, labelTo }
  7. : IProps) {
  8. const currenciesValues: any[] = [];
  9. useEffect(() => {
  10. getCurrenciesValues();
  11. }, [choiceFrom, choiceTo])
  12. async function getCurrenciesValues () {
  13. const promise = await Promise.all(defaultData.map(async (number) => {
  14. const { result } = await fetchFromAPI(`convert?from=${choiceFrom}&to=${choiceTo}&amount=${number.value}`);
  15. return result
  16. }))
  17. currenciesValues.push(promise);
  18. console.log("Inside currenciesValues", currenciesValues);
  19. }
  20. console.log("Outside currenciesValues", currenciesValues);

这是我在控制台中得到的回应。
enter image description here
如有必要,我还将连接到此存储库:https://github.com/VladyslavMazurets/currency_converter/blob/main/src/components/CurrencyTable.tsx
如有任何帮助,我将不胜感激。

xkftehaa

xkftehaa1#

我建议您是否要在Reaction组件中维护一个值以使用状态。所以你可以把你所拥有的东西改成这样

  1. const defaultData = [
  2. { value: 1 }, { value: 5 }, { value: 10 },
  3. { value: 25 }, { value: 50 }, { value: 100 },
  4. { value: 500 }, { value: 1000 }, { value: 5000 },
  5. { value: 10000 }, { value: 50000 }];
  6. function CurrencyTable({ choiceFrom, choiceTo, labelFrom, labelTo }
  7. : IProps) {
  8. const [currenciesValues, setCurrenciesValues] = useState([])
  9. useEffect(() => {
  10. getCurrenciesValues();
  11. }, [choiceFrom, choiceTo])
  12. useEffect(() => {
  13. console.log("Outside currenciesValues", currenciesValues);
  14. }, [currenciesValues])
  15. async function getCurrenciesValues () {
  16. const promise = await Promise.all(defaultData.map(async (number) => {
  17. const { result } = await fetchFromAPI(`convert?from=${choiceFrom}&to=${choiceTo}&amount=${number.value}`);
  18. return result
  19. }))
  20. setCurrenciesValues([...currencyValues, promise]);
  21. console.log("Inside currenciesValues", currenciesValues);
  22. }
  23. console.log("Outside currenciesValues", currenciesValues);

然后将您的控制台日志移动到useEffect中

展开查看全部

相关问题