1

我如何在 redux 操作中首先进行 api 调用,然后调度 GET_TODO?

// first the api call has to be made,

    export function getTodos() {
    return {
          type: 'GET_TODOS',
          promise: request.get(API_URL)
      }
    }

然后它需要解析响应

// using https://github.com/Leonidas-from-XIV/node-xml2js
parseString(res, function (err, result) {
          // data gets parsed here
});

然后它必须发送 raise 事件。我尝试如下,但它抛出错误

const request = axios.get(url).then(res=>{
parseString(res, function (err, result) {
if(result){
      dispatch({
         type: GET_TODOS,
      data:result
    })
}
if(err) throw err
   });
}).catch(err=>console.error(error))
  };

我得到以下错误

错误:操作必须是普通对象。使用自定义中间件进行异步操作。

4

1 回答 1

4

使用thunk 中间件。您的操作如下所示:

export const GET_TODOS = 'GET_TODOS'
export const GET_TODOS_SUCCESS = 'GET_TODOS_SUCCESS'
export const GET_TODOS_FAILURE = 'GET_TODOS_FAILURE'

export function getTodos() {
  return dispatch => {
     dispatch({
        type: GET_TODOS
     })

     fetch(url) // or whatever way you're making API call
        .then(res => {
           parseString(res, (err, result) => {
              if (err) {
                 throw err
              }

              dispatch({
                 type: GET_TODOS_SUCCESS,
                 payload: result
              })
           })
        })
        .catch(err => {
              dispatch({
                 type: GET_TODOS_FAILURE,
                 payload: err
              })
        })
  }
}
于 2016-09-30T08:31:08.297 回答