简体   繁体   中英

Cannot read property 'then' of undefined

So I'm using react + redux, and I'm continuing to get the following error: "Cannot read property 'then' of undefined". For some reason the promise isn't being returned. I'm also particularly new to using redux thunk.

Reducer

import { merge } from 'lodash';
import  * as APIutil  from '../util/articles_api_util';


import {
  ArticleConstants
} from '../actions/article_actions';

const ArticlesReducer = (state = {}, action) => {
  switch (action.type) {
    case ArticleConstants.RECEIVE_ALL_ARTICLES:
    debugger
    return merge({}, action.articles);
    default:
      return state;
  }
};

export default ArticlesReducer;

Store

import { createStore, applyMiddleware } from 'redux';
import RootReducer from '../reducers/root_reducer';
import thunk from 'redux-thunk';

import  * as APIUtil  from '../util/articles_api_util';

export const ArticleConstants = {
    RECEIVE_ALL_ARTICLES: "RECEIVE_ALL_ARTICLES",
    REQUEST_ALL_ARTICLES: "REQUEST_ALL_ARTICLES"
}

Actions

export function fetchArticles() {
  return function(dispatch) {
    return APIUtil.fetchArticles().then(articles => {
      dispatch(receiveAllArticles(articles));
    }).catch(error => {
      throw(error);
    });
  };
}


export const requestAllArticles= () => ({
    type: REQUEST_ALL_ARTICLES
});


export const receiveAllArticles = articles => ({
    type: RECEIVE_ALL_ARTICLES,
    articles
});

    const configureStore = (preloadedState = {}) => (
      createStore(
        RootReducer,
        preloadedState,
        applyMiddleware(thunk)
      )
    );


    export default configureStore;

APIUtil

export const fetchArticles = (success) => {
  $.ajax({
        method: 'GET',
        url: `/api/articles`,
        success,
        error: ()=> (
        console.log("Invalid Article")
      )
    });
};

Arrow functions only do implicit return s if you leave off the curly braces. As soon as you include curly braces, you have defined a function body, and need to explicitly return a value.

Your fetchArticles function is written as an arrow function with curly braces. However, you are not explicitly returning the result of the $.ajax() call. So, the return value of the function is undefined , and there's no promise returned that you can chain off of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM