redux thunk 调用两个不同的 api 请求
redux thunk calling two different api requests
试图在一个动作中调用两个 api。当一个完成时调用另一个然后在最后一个将其传递给减速器。
看起来我的 getAttending 是在 post 的同时被调用的,而不是在 post 完成之后。我是 redux-thunk 的新手,我想我可以在完成后一个接一个地调用它们。
export function postDeclined(id){
let post = axios.post(blaBla.com);
let getAttending = axios.get(attending.com);
return (dispatch) => {
post.then(()=>{
getAttending.then(({data})=>{
dispatch({
type: type.NOT_GOING,
payload: data.data
});
});
});
}
}
尝试像这样进行 api 调用:
export function postDeclined(id){
return (dispatch) => {
axios.post(blaBla.com).then(()=>{
axios.get(attending.com).then(({data})=>{
dispatch({
type: type.NOT_GOING,
payload: data.data
});
});
});
}
}
当您 "declared" 调用时,您实际上是在调用 API... 所以它正在执行异步...
我会将 async/await 添加到您的 babel 配置中。使 reading/debugging 这些事情变得容易得多。
export const postDeclined => (id) => async (dispatch) => {
const post await axios.post(blaBla.com);
const getAttending = await axios.get(attending.com);
return dispatch({
type: type.NOT_GOING,
payload: getAttending.data
});
};
代码示例存在一个非常常见的问题。该函数同时做两件事:调用 api 和分派一个动作。另外,请注意,您可以链接 Promises,不需要中间回调:
export const postDeclined = id =>
axios.post(blaBla.com).then(axios.get(attending.com));
export const notifyNotGoing = dispatch => promisedResult =>
promisedResult.then(({data}) =>
dispatch({
type: type.NOT_GOING,
payload: data.data
})
);
然后你可以这样调用你的函数:
notifyNotGoing(dispatch)(postDeclined(2))
或者使用组合和柯里化(我个人更喜欢Ramda)
const prog = compose(notifyNotGoing(dispatch), postDeclined)
prog(2)
试图在一个动作中调用两个 api。当一个完成时调用另一个然后在最后一个将其传递给减速器。 看起来我的 getAttending 是在 post 的同时被调用的,而不是在 post 完成之后。我是 redux-thunk 的新手,我想我可以在完成后一个接一个地调用它们。
export function postDeclined(id){
let post = axios.post(blaBla.com);
let getAttending = axios.get(attending.com);
return (dispatch) => {
post.then(()=>{
getAttending.then(({data})=>{
dispatch({
type: type.NOT_GOING,
payload: data.data
});
});
});
}
}
尝试像这样进行 api 调用:
export function postDeclined(id){
return (dispatch) => {
axios.post(blaBla.com).then(()=>{
axios.get(attending.com).then(({data})=>{
dispatch({
type: type.NOT_GOING,
payload: data.data
});
});
});
}
}
当您 "declared" 调用时,您实际上是在调用 API... 所以它正在执行异步...
我会将 async/await 添加到您的 babel 配置中。使 reading/debugging 这些事情变得容易得多。
export const postDeclined => (id) => async (dispatch) => {
const post await axios.post(blaBla.com);
const getAttending = await axios.get(attending.com);
return dispatch({
type: type.NOT_GOING,
payload: getAttending.data
});
};
代码示例存在一个非常常见的问题。该函数同时做两件事:调用 api 和分派一个动作。另外,请注意,您可以链接 Promises,不需要中间回调:
export const postDeclined = id =>
axios.post(blaBla.com).then(axios.get(attending.com));
export const notifyNotGoing = dispatch => promisedResult =>
promisedResult.then(({data}) =>
dispatch({
type: type.NOT_GOING,
payload: data.data
})
);
然后你可以这样调用你的函数:
notifyNotGoing(dispatch)(postDeclined(2))
或者使用组合和柯里化(我个人更喜欢Ramda)
const prog = compose(notifyNotGoing(dispatch), postDeclined)
prog(2)