簡體   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