0

目前正在从事一个宠物项目,该项目在完成类似的代码后调用 API 生成外汇对列表,并想尝试独立完成。

该代码昨天运行良好,目前正在为使用 redux 工具包从 API 调用检索的数据吐出未定义的类型错误。在这方面仍然是一个新手,并且会感谢任何帮助和指导来解决这个问题。

使用的 API 可以在这里找到:https ://rapidapi.com/twelvedata/api/twelve-data1/

抱歉,如果它变得太长,但是每当我刷新页面时都会发生错误。目前,我正在处理 Forex.jsx 中的整个 fxpairs.data.forEach 的注释以加载页面,然后取消注释以加载成功的连接(如果有意义)。

这是来自开发者控制台的未定义错误: 在此处输入图像描述

这是我在 12DataApi.js 中调用 api 的代码(由于明显的原因省略了键):

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const twelveDataApiHeaders = { 
    'x-rapidapi-host': 'twelve-data1.p.rapidapi.com',
    'x-rapidapi-key': ''
}

const baseUrl = 'https://twelve-data1.p.rapidapi.com/';

const createRequest = (url) => ({ url, headers: twelveDataApiHeaders});

export const twelveDataApi = createApi({
    reducerPath: 'twelveDataApi',
    baseQuery: fetchBaseQuery({ baseUrl }),
    endpoints: (builder) => ({
        getPairsList: builder.query({
            query: () => createRequest(`/forex_pairs`),
        }),
        getExchangeRate: builder.query({
            query: (symbol) => createRequest(`/exchange_rate?symbol=${symbol}`), //symbol has to be in the form USD/JPY
        })
    })
});

export const { 
    useGetPairsListQuery,
    useGetExchangeRateQuery,
} = twelveDataApi;

这是 Forex.jsx,使用 fxpairs 时发生错误(省略 html,因为那不是问题):

import { useGetPairsListQuery, useGetExchangeRateQuery } from '../services/twelveDataApi';

const Forex = () => {
    const symbol = 'USD/JPY';
    const { data: fxpairs, isFetching } = useGetPairsListQuery();

    console.log(fxpairs); 
    // pairs info manipulation 
    const otherPairs = [];
    const major = ['EUR/USD', 'USD/JPY', 'GBP/USD', 'USD/CHF', 'AUD/USD', 'USD/CAD', 'NZD/USD']; //major pairs to be placed on top 
    fxpairs.data.forEach(pair => { // <= this is where uncaught typeerror occured
        if (!major.includes(pair.symbol)) {
            otherPairs.push(pair.symbol);
        };
    });
    const allPairs = major.concat(otherPairs);
    const pairObj = {}; 
    allPairs.forEach(pair => { 
        pairObj[pair] = {};
        pairObj[pair]['symbol'] = pair;
        pairObj[pair]['from'] = pair.split("/")[0];
        pairObj[pair]['to'] = pair.split("/")[1];
    });

    // loading state
    if(isFetching) return "Loading...";

4

1 回答 1

0

我发现答案是由于isFetching声明的位置。

使用开发人员工具和 redux 调试器,可以看到正在进行多个 API 调用,它们要么被拒绝,要么保持打开状态。为了检查 API 调用是否仍然处于活动状态,isFetching需要该语句,因此在获取后的任何形式的数据操作都应该在该isFetching语句之后。

因此,我已将所有 API 调用移至顶部,然后是isFetching检查打开请求的语句,然后最终操作数据以满足我的需要。

** 为清楚起见进行了编辑

于 2022-01-26T14:22:32.780 回答