Redux-Thunk“操作必须是普通对象。 使用自定义中间件进行asynchronous操作。“
使用Thunk中间件创build我的商店
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/') ); }
但是出现错误:“操作必须是普通对象,使用自定义中间件进行asynchronous操作”。
这个设置有什么问题? 我曾尝试调用compose(applyMiddleware(thunk))
但无济于事。
你的代码看起来不错,只是它缺less如何处理错误(承诺拒绝)。 你的api可能会返回错误,你不处理它可能导致该错误消息。
尝试添加
export function getArticle(url) { return function (dispatch) { fetchArticle(url) .then(article => dispatch(setArticle(article))) .catch(err => dispatch({ type: 'SOME_ERROR', err })); }; }
更改
return function (dispatch) { fetchArticle(url).then( article => dispatch(setArticle(article)), ); };
至
return function (dispatch) { return fetchArticle(url).then( article => dispatch(setArticle(article)), ); };
尝试以下操作:
export function getArticle(url) { return fetchArticle(url).then( article => dispatch(setArticle(article)), ); }