首页 > 解决方案 > REDUX - 如何导入返回 Promise 的 API 函数并将其添加到动作创建器的有效负载中

问题描述

我的 Redux 至少可以说生锈了,我正在尝试从返回 Promise 的 API 导入函数。我想将此 Promise 添加到动作创建者的有效负载中,但它抱怨说TypeError: Cannot read property 'getBetList' of undefined

这是我的动作创建者:

import { getBetList, getLatestPrices } from '../api/index';
export const GET_BET_LIST = 'GET_BET_LIST';
export const GET_LATEST_PRICES = 'GET_LATEST_PRICES';


export function fetchBetList() {
  const response = this.getBetList();

  return {
    type: GET_BET_LIST,
    payload: response
  }
}

export function fetchLatestPrices() {
  const response = this.getLatestPrices();

  return {
    type: GET_LATEST_PRICES,
    payload: response
  }
}

我假设从 API 收到的 Promise 将在有效负载上可用,将通过 redux-promise 流动,最后我得到我需要的数据,但它因无法读取 getBetList 的错误而停止?我在这里的导入哪里做错了?

标签: redux

解决方案


您应该直接使用getBetList& getLatestPrices,因为您将它导入到文件的顶部。从下面的行中删除this将修复您的错误。

const response = this.getBetList();
                 ^^^^

和这里一样

const response = this.getLatestPrices();

顺便说一句,它也不起作用,您应该像这样使用异步流:

export function fetchLatestPrices() {
  return (dispatch) => {
    getLatestPrices()
      .then(response => dispatch({type: GET_LATEST_PRICES, payload: response}));

  }
}

有关更多信息async actions


推荐阅读