gpt4 book ai didi

node.js - 如何在 redux 操作中链接 Promise

转载 作者:太空宇宙 更新时间:2023-11-03 22:51:48 24 4
gpt4 key购买 nike

如何在 redux 操作中首先进行 api 调用,然后分派(dispatch) 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))
};

我遇到以下错误

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

最佳答案

使用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
})
})
}
}

关于node.js - 如何在 redux 操作中链接 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39783210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com