【问题标题】:Cannot read property `.then` of undefined with axios and react in actions无法使用 axios 读取未定义的属性“.then”并在操作中做出反应
【发布时间】:2018-02-27 13:16:09
【问题描述】:

我在一个动作中使用 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,
    });
  };
}

【问题讨论】:

    标签: reactjs promise axios


    【解决方案1】:

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

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2017-12-09
      • 2021-12-25
      • 2021-09-24
      • 1970-01-01
      • 2021-01-04
      • 2018-05-24
      • 2019-01-29
      • 1970-01-01
      • 2017-04-21
      相关资源
      最近更新 更多