首页 文章

Redux-Thunk“动作必须是普通对象 . 使用自定义中间件进行异步操作 . “

提问于
浏览
2

使用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() 上调用dispatch

componentDidMount(){
  this.props.dispatch(
    getArticle('http://api.example.com/')
  );
}

但是得到错误:“操作必须是普通对象 . 使用自定义中间件进行异步操作 . ”

这个设置有什么问题?我试过打电话 compose(applyMiddleware(thunk)) 但无济于事 .

4 回答

  • 0

    您的代码看起来没问题,但它缺少如何处理错误(承诺拒绝) . 您的api可能会返回错误而您没有处理它可能导致该错误消息 .

    尝试添加

    export function getArticle(url) {
      return function (dispatch) {
        fetchArticle(url)
          .then(article => dispatch(setArticle(article)))
          .catch(err => dispatch({ type: 'SOME_ERROR', err }));
      };
    }
    
  • 2

    更改

    return function (dispatch) {
        fetchArticle(url).then( 
          article => dispatch(setArticle(article)),
        );
      };
    

    return function (dispatch) {
        return fetchArticle(url).then( 
          article => dispatch(setArticle(article)),
        );
      };
    
  • 0

    请尝试以下方法:

    export function getArticle(url) {
        return fetchArticle(url).then( 
          article => dispatch(setArticle(article)),
        );  
    }
    
  • 0

    在Redux中,每个动作都必须返回一个对象 .

    你可以使用:

    export const getArticle= url=> dispatch => {
     fetchArticle(url)
       .then(res =>
         dispatch({ type: SET_ARTICLE, payload: res.data })
       )
       .catch(err =>
         dispatch({
           type: GET_ERRORS,
           payload: err.response.data
         })
       );
    };
    

相关问题