創建我的商店與咚中間件Redux-Thunk「操作必須是普通對象,使用自定義中間件進行異步操作。」
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(
reducer,
initialState,
applyMiddleware(thunk)
);
,創造我的作用,這要求一個承諾
export function getArticle(url) {
return function (dispatch) {
fetchArticle(url).then(
article => dispatch(setArticle(article)),
);
};
}
function fetchArticle(url) {
return new Promise((resolve, reject) => {
request
.get(url)
.end((err, res) => {
if (err || !res.ok) {
reject('Oh no! error');
} else {
resolve(res.body);
}
});
})
}
export function setArticle(article){
return {
type: constants.SET_ARTICLE,
article
}
}
在我的文章成分,我呼籲調度上componentDidMount()
componentDidMount(){
this.props.dispatch(
getArticle('http://api.example.com/')
);
}
但得到錯誤:「操作必須是普通對象,使用自定義中間件進行異步操作。」
這個設置有什麼問題?我曾嘗試致電compose(applyMiddleware(thunk))
但無濟於事。
這可能聽起來愚蠢的,但要確保你有終極版,安裝的thunk,'NPM安裝終極版,thunk'。 console.log'thunk'確保存在。 你的代碼看起來很好,它看起來像thunk沒有註冊。 –