【问题标题】:async await into actionCreator, should i return the result?异步等待到 actionCreator,我应该返回结果吗?
【发布时间】:2018-11-27 07:54:20
【问题描述】:

在我的 actionCreators 中,我在操作上调用了一些其他 API 端点,例如UPDATE_CART_ITEM

一开始我是这样使用axios的return axios()...

export const login = (username, password) => (dispatch) => {
  dispatch(requestLogin())
  const URL = `${USERS_URL}?username=${username}&password=${password}`
  return axios(URL)
    .then((response) => {
      return response.data
    })
    .then((user) => {
      dispatch(loginSuccess(user))
      // save the user on localStorage
      localStorage.setItem('user', JSON.stringify(user))
      // direct the logedin user to the games page
      history.push('/')
    })
    .catch(() => {
      return dispatch(loginFailure())
    })
}

现在我像这样使用 async/await:

// On payload i have the obj: {prId: 'xxxxx'}
export const updateCartItem = (payload) => async (dispatch) => {
    const response = await fetch('cart/update',
    {
      body: JSON.stringif(payload),
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      method: 'POST',
    })

  // I m not sure if i have to return the result
  const result = await response.json()

  // I dispatch the action with the payload
  await dispatch(return {
    payload,
    type: UPDATE_CART_ITEM,
  })
} catch (err) {
  dispatch(cartActionFail(err))
}
 }

那么,在updateCartItem 函数内部,我应该如何处理result 呢?
由于我将payload传递给reducer,看来我不需要它。

【问题讨论】:

    标签: javascript reactjs redux fetch state


    【解决方案1】:

    你可能想做这样的事情:

    dispatch({ payload: response, type: UPDATE_CART_ITEM })

    dispatch(return { /*...*/ }) 据我所知没有意义,dispatch() 不会返回承诺,因此等待它没有意义。

    一般来说,如果你想用 async/await 替换 Promise 链,那么你想用 const bar = await foo; baz(bar); 替换 foo.then(bar => { baz(bar); })

    【讨论】:

      【解决方案2】:

      如果您需要立即使用您的结果,那么您应该调度一个类似 UPDATE_CART_ITEM_SUCCEED 的操作,否则什么也不做。

      顺便说一句,我建议您使用 redux-saga 或 redux-thunk 来处理您的应用程序副作用,例如 API 调用。

      【讨论】:

        【解决方案3】:

        如果您为动作创建者使用相同的有效负载,如果您的后端出现问题会怎样?您的后端不会改变,但您的状态不会意识到这一点并使用有效负载进行自我更新。这就是为什么你应该在这里使用一些错误检查。另外,我个人使用最后一个结果作为我的动作创建者的有效负载,而不是原始有效负载。

        export const updateCartItem = payload => async ( dispatch ) => {
          try {
            const response = await fetch(
              "cart/update",
              {
                body: JSON.stringif( payload ),
                headers: {
                  Accept: "application/json",
                  "Content-Type": "application/json",
                },
                method: "POST",
              }
            );
            if ( !response.ok ) { throw new Error( "response error" ); }
            const result = await response.json();
            return dispatch( {
              payload: result,
              type: UPDATE_CART_ITEM,
            } );
          } catch ( error ) {
            return dispatch( cartActionFail( error.message ) );
          }
        };
        

        您可以根据需要更改和增强此逻辑。正如@vkarpov15 指出的那样,调度没有明确使用return,它也没有返回承诺,因此你不需要在那里等待。

        【讨论】:

        • 确实在这种情况下,我可以使用“结果”作为有效负载。但是 try{}catch() 不是给我错误是后端发生了什么吗?
        • 我已经编辑了我的答案。是的,如果发生错误,你是对的,try/catch 会捕捉到这一点,但如果出现问题,你的状态会以某种方式改变而没有任何错误。当然,这只是个人处理逻辑的方式。使用这样的结果是我的偏好,因为我可以看到回到我的状态。
        猜你喜欢
        • 2020-02-10
        • 2019-10-20
        • 1970-01-01
        • 2013-07-27
        • 1970-01-01
        • 2020-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多