如何在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
});
然后它必须发送加注事件。我尝试如下,但它抛出错误
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))
};
我收到以下错误
错误:操作必须是普通对象。使用自定义中间件进行异步操作。
答案 0 :(得分:4)
使用thunk middleware。以下是您的操作的样子:
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
})
})
}
}