在 axiosreact 中调用 .then 来调度

问题描述 投票:0回答:1

我有下面的代码,请问有什么办法可以去掉Promise.all,直接调用dispatch(setAnimalCharacteristics)?

   ....  
 then(() => {
 return Promise.all([
          dispatch(setAnimalCharacteristics(animalform))
        ])
          .then(() => {
            history.push("/animals);
          })

有没有办法去掉Promise.all 然后直接调用dispatch(setAnimalCharacteristics)?

我试着运行这个。

 then(() => {
   return dispatch(setAnimalCharacteristics(animalform)).then(() => {

然后我得到了错误信息

Uncaught (in promise) TypeError: Cannot read property 'then' of undefined
reactjs promise axios thunk
1个回答
0
投票

这应该是可行的。

await dispatch(setAnimalCharacteristics(animalform))

history.push("/animals);

在你的代码中,我唯一看不到的部分是它被调用的函数,在那里你需要添加关键字 async 所以你可以使用 await

但这里有一个猜测。

const yourFunction async = () => {
   await dispatch(setAnimalCharacteristics(animalform))

   history.push("/animals);
}

0
投票

如果你想在派发动作后进行导航,你其实不必嵌套then()函数。有几种方法可以解决这个问题。

  1. Then可以像下面这样链起来。
.then(() => dispatch(setAnimalCharacteristics(animalform))).then(() => history.push("animal);)
  1. 在你的setAnimalCharacteristics函数的最后写上history.push。在API调用完成后,我们最常用这个模式来导航。

希望能帮到你!

© www.soinside.com 2019 - 2024. All rights reserved.