所以我正在使用react + redux,并且我继续收到以下错误:“无法读取未定义的属性'then'”。由于某种原因, promise 没有得到返回。我对使用 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;
商店
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"
}
操作
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")
)
});
};
最佳答案
如果省略大括号,箭头函数只会执行隐式返回。一旦包含花括号,您就定义了一个函数体,并且需要显式地返回
一个值。
您的 fetchArticles
函数被编写为带有大括号的箭头函数。但是,您没有显式返回 $.ajax()
调用的结果。因此,该函数的返回值是未定义
,并且没有返回可以链接的 promise 。
关于javascript - 无法读取未定义的属性 'then',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41358159/