javascript - 类型 'data' 上不存在属性 'AxiosResponse<any> | undefined'

标签 javascript reactjs typescript redux

我的操作抛出错误:

// ACTIONS
export const startGetPrices = () => (dispatch: any) => getLatest().then((res) => {
  console.log('res', res);
  const { data } = res; // <-- error highlighted data
  const { rates } = data;
  dispatch(actionGetPrices(rates));
});

enter image description here

在同一个文件中,我有以下接口(interface):

export interface IPricesRes {
  data: IPriceData
}

export interface IPriceData {
  base: string;
  date: string;
  rates: any;
  success: boolean;
  timestamp: number;
}

在我使用该接口(interface)的组件中:

import React from 'react'
import { connect } from 'react-redux'

import { startGetPrices, IPricesRes } from '../store'
import { CurrencySelector, Header, Prices, Navigation } from '../components'

interface IProps {
  fiatPrices: [];
  startGetPrices(): IPricesRes; // <-- the res interface
}

class FiatWallet extends React.PureComponent<IProps> {
  componentDidMount() {
    console.log('FiatWallet componentDidMount...');
    this.props.startGetPrices();
  }

  public render() {
    const { fiatPrices } = this.props;
    return (
      <section>
        <CurrencySelector />
        <Header />
        <Prices prices={fiatPrices} />
        <Navigation />
      </section>
    );
  }     
}

const mapDispatchToProps = (dispatch: any) => ({
  startGetPrices: () => dispatch(startGetPrices())
});

const mapStateToProps = (state: any) => ({
  fiatPrices: state.fiatPrices,
  wallets: state.fiatPrices,
  defaultCurrency: state.defaultCurrency
});

export const BoardJest = FiatWallet;

export default connect(mapStateToProps, mapDispatchToProps)(FiatWallet);

它告诉我类型 AxiosResponse<any> 上不存在数据我的问题是如何正确输入?

我在哪里使用 IPricesResIPriceData


我的整个 store.ts 文件:

import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunkMiddleware from 'redux-thunk'

import { getLatest } from './services/api'

export interface IinitialState {
  fiatPrices: [];
  wallets: [];
  defaultCurrency: string;
}

export interface IPricesRes {
  data: IPriceData
}

export interface IPriceData {
  base: string;
  date: string;
  rates: any;
  success: boolean;
  timestamp: number;
}

const initialState = {
  fiatPrices: [],
  wallets: [],
  defaultCurrency: ''
}

// ACTION TYPES
export const actionTypes = {
  GET_PRICES: 'GET_PRICES'
}

// REDUCER
export const reducer = (state = initialState, action: any) => {
  switch (action.type) {
    case actionTypes.GET_PRICES: {
      const { rates } = action;
      return {
        ...state,
        fiatPrices: rates
      };
    }

    default:
      return state;
  }
}

// ACTIONS CREATORS
export const actionGetPrices = (data: any) => ({
  type: actionTypes.GET_PRICES,
  assets: data
});

// ACTIONS
export const startGetPrices = () => (dispatch) => getLatest().then((res) => {
  console.log('res', res);
  const { data } = res;
  const { rates } = data;
  dispatch(actionGetPrices(rates));
});

// @ts-ignore
export function initializeStore(initialState: IinitialState = initialState) {
  return createStore(
    reducer,
    initialState,
    composeWithDevTools(applyMiddleware(thunkMiddleware))
  )
}

服务/API 其中 getLatests()是:

import axios from 'axios'

const fixerAPI = 'http://data.fixer.io/api/';
const fixerKey = '25a1ad0f5f253du7131b68cd1...';

export const getLatest = async () => {
  const fixer = axios.create({
    baseURL: fixerAPI,
    params: {
      // base: 'USD',
      access_key: fixerKey
    }
  });

  try {
    const prices = await fixer.get('latest');
    return prices;
  } catch (err) {
    console.error(err);
  }
}

最佳答案

我能够通过添加一个 converter.ts util 来绕过这个错误,但是如果有更好的答案请发帖加分!

// ACTIONS

export const startGetPrices = () => (dispatch: any) => getLatest().then((res) => {
  const ratesArray = converters.ratesIntoArray(res);
  dispatch(actionGetPrices(ratesArray));
});

// utils/converters.ts

// Takes rates { key : value } pairs and converts into Array.
export const ratesIntoArray = ({ data: { rates } }: any) =>
  Object.keys(rates).map(data => [data, rates[data]]);

关于javascript - 类型 'data' 上不存在属性 'AxiosResponse<any> | undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54485166/

相关文章:

typescript - 无论如何在 typescript 中做嵌套的 Pick<> 类型

javascript - 有没有办法为 Jasmine 单元测试(Angular 4)提供基类?

javascript - 如何使用jquery检查文件是否被修改

javascript - ReactJS , setState 问题 onChange 事件

javascript - 服务器端未定义 renderProps/React/React-Router + Node/Express.js 的同构渲染

javascript - React-Router - 链接到同一页面不触发页面卸载

javascript - 使用 Angular 8 Material Sidenav 进行响应式导航?

javascript - 如何修复 'window.minimize() is not a function' ?

javascript - D3.js 饼图周围的 flex 文本

Javascript:带参数的动态函数