无法使用 axios 读取未定义的 属性 `.then` 并在操作中做出反应

Cannot read property `.then` of undefined with axios and react in actions

我在一个动作中使用 axios 并尝试通过链接动作调用该动作。我将在这里展示我正在尝试做的事情:

this.props.fetchOffers().then(() => {
        this.props.filter(this.props.filterOption);
      });

但是我得到一个错误:Cannot read property 'then' of undefined

我没有得到的是,在这个函数的正下方,我有另一个动作正在做同样的事情并且工作得很好。

  this.props.sortOffers(value).then(() => {
      this.props.filter(this.props.filterOption);
    });

这是一个工作版本。

这是动作文件:

import axios from 'axios';
import { reset } from 'redux-form';

import { FETCH_OFFERS, SORT_OFFERS, FETCH_OFFER, GET_FILTER, PAYMENT_TYPE } from './types';

export function paginateOffers(indexPosition, numberOfItems) {
  return (dispatch) => {
    axios
      .get('/API/offers/pagination', {
        params: {
          position: indexPosition,
          number: numberOfItems,
        },
      })
      .then((response) => {
        dispatch({ type: FETCH_OFFERS, payload: response.data });
      })
      .catch((error) => {
        console.error(error);
      });
  };
}

export function fetchOffers() {
  return dispatch => {
    axios
      .get('/API/offers')
      .then((response) => {
        dispatch({ type: FETCH_OFFERS, payload: response.data });
      })
      .catch((err) => {
        console.error(err);
      });
  };
}

export function fetchOffer(id) {
  return (dispatch) => {
    axios
      .get(`/API/offers/${id}`)
      .then((response) => {
        dispatch({ type: FETCH_OFFER, payload: response.data.result });
      })
      .catch((err) => {
        console.error(`ERROR: ${err}`);
      });
  };
}

export function sortOffers(params) {
  const { price, title, category, type } = params;
  return dispatch =>
    axios
      .get('/API/offers/sort', {
        params: { price, title, category, type },
      })
      .then((response) => {
        dispatch({
          type: SORT_OFFERS,
          payload: response.data,
          sortOptions: params,
        });
        dispatch({
          type: PAYMENT_TYPE,
          payment: type,
        });
        dispatch(reset('sorter'));
      })
      .catch((err) => {
        console.error(err);
      });
}

export function getFilterOption(option) {
  return (dispatch) => {
    dispatch({
      type: GET_FILTER,
      option,
    });
  };
}

您没有在 fetchOffers 操作创建器中返回承诺。请注意您声明粗箭头函数的方式的细微差别。

试试这个:

export function fetchOffers() {
  return dispatch => 
    axios
      .get('/API/offers')
      .then((response) => {
        dispatch({ type: FETCH_OFFERS, payload: response.data });
      })
      .catch((err) => {
        console.error(err);
      });
}