簡體   English   中英

Redux thunk:等待異步函數調度

[英]Redux thunk: wait for async function to dispatch

我正在創建一個React Native應用程序並使用redux和redux-thunk來實現我的API請求。 我想知道如何等待我的行動被派遣,並確保我的狀態已經在異步thunk邏輯中更新。 如果我理解正確, await將等待thunk的結束,但是尚未調度該動作。 雖然,正如您在我的使用中所看到的,我需要修改狀態以相應地繼續執行其余代碼。

動作/ user.js的

export const tryLogin = (
  email: string,
  password: string,
  sessionToken: string = ''
): Function => async (dispatch: Function) => {
  const logUser = () => ({ type: LOG_USER })

  const logUserSuccess = (data: any, infos: any) => ({
    type: LOG_USER_SUCCESS,
    data,
    infos,
  })

  const logUserError = (signinErrorMsg: string) => ({
    type: LOG_USER_ERROR,
    signinErrorMsg,
  })

  dispatch(logUser())

  try {
    { /* Some API requests via axios */ }

    dispatch(logUserSuccess(responseJson, infos))
    return true
  } catch (error) {
    { /* Error handling code */ }

    dispatch(logUserError(error.response.data.error))
    return false
}

減速器/ user.js的

case LOG_USER:
  return {
    ...state,
    isLoggingIn: true,
  }
case LOG_USER_SUCCESS:
  return {
    ...state,
    isLoggingIn: false,
    data: action.data,
    infos: action.infos,
    error: false,
    signinErrorMsg: '',
  }
case LOG_USER_ERROR:
  return {
    ...state,
    isLoggingIn: false,
    error: true,
    signinErrorMsg: action.signinErrorMsg,
  }

RegisterScreen.js

if (await trySignup(
    emailValue,
    firstNameValue,
    lastNameValue,
    passwordValue,
    birthdateValue,
    genderValue
  )
) {
  if (userReducer.data) {
    navigation.navigate('Secured')
  }

在Redux中,當Action被調度到商店時,它將使用新的props自動更新UI的狀態。

您可以在reducer signUpSuccess添加一個類似於isLoggingIn標志的標志,而不是觀察已調度的操作,並監聽componentDidUpdate生命周期方法中的更改。

trySignup可以單獨調用(如在事件,formSubmit,按鈕單擊等)

RegisterScreen.js

class RegisterScreen extends React.Component{
...
componentDidUpdate(prevProps) {
  if (prevProps.signUpSuccess !== this.props.signUpSuccess){
    if (this.props.signUpSuccess) {
      navigation.navigate('Secured')
    }
  }
}
...
}
const mapStateToProps = (state) => ({
  signUpSuccess: state.userReducer.signUpSuccess,
});

export default connect(mapStateToProps)(RegisterScreen);

如果我理解正確,await將等待thunk的結束,但是尚未調度該動作。

  • 如果在道具中發生任何更改,渲染可以更新,因此在渲染方法中提取道具並根據道具中的更改更新UX。
  • 我建議使用React本機調試器來檢查您的操作和當前保存的狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM