在axios / react中的调度上调用.then

时间:2020-06-11 21:18:46

标签: reactjs promise axios thunk

我有以下代码:

   ....  
 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

2 个答案:

答案 0 :(得分:0)

这应该有效:

await dispatch(setAnimalCharacteristics(animalform))

history.push("/animals);

我唯一看不到的代码部分是在需要添加关键字async的地方调用的函数,因此您可以使用await

但这是一个猜测:

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

   history.push("/animals);
}

答案 1 :(得分:0)

如果您要在分派操作后进行导航,则实际上不必嵌套then()函数。有几种解决方法。

  1. 然后可以按如下所示进行链接。

.then(() => dispatch(setAnimalCharacteristics(animalform)))
.then(() => history.push("/animals);)

  1. 最后在您的setAnimalCharacteristics函数中写入history.push。在API调用完成后,我们最多使用此模式进行导航。

希望这会有所帮助!