目前正在从事一个宠物项目,该项目在完成类似的代码后调用 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...";