使用 Thunk 中间件创建我的商店
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(
reducer,
initialState,
applyMiddleware(thunk)
);
并创建调用 promise 的操作
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))
但无济于事。
最佳答案
您的代码看起来不错,只是缺少如何处理错误( promise 拒绝)。您的 api 可能会返回错误,而您没有处理它,这可能会导致该错误消息。
尝试添加
export function getArticle(url) {
return function (dispatch) {
fetchArticle(url)
.then(article => dispatch(setArticle(article)))
.catch(err => dispatch({ type: 'SOME_ERROR', err }));
};
}
关于node.js - Redux-Thunk "Actions must be plain objects. Use custom middleware for async actions.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43772168/