繁体   English   中英

异步等待进入actionCreator,我应该返回结果吗?

[英]async await into actionCreator, should i return the result?

在我的actionCreator中,我调用了一些其他的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传递给减速器,因此似乎不需要它。

您可能想要执行以下操作:

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

就我所知, dispatch(return { /*...*/ })没有任何意义,而dispatch()不会返回promise,因此没有必要等待它。

通常,如果要用async / await替换promise链,则要用const bar = await foo; baz(bar);替换foo.then(bar => { baz(bar); }) const bar = await foo; baz(bar); const bar = await foo; baz(bar);

如果您需要立即使用结果,则应该分派UPDATE_CART_ITEM_SUCCEED之类的操作,否则什么也不做。

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

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

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指出的那样,dispatch不会显式使用return ,也不会返回promise,因此您不需要在那里等待。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM