javascript - Redux thunk : wait for async function to dispatch

标签 javascript reactjs react-native redux redux-thunk

我正在创建一个 React Native 应用程序并使用 redux 和 redux-thunk 来实现我的 API 请求。我想知道如何等待我的操作被分派(dispatch)并确保我的状态已在异步 thunk 逻辑中更新。如果我理解正确,await 将等待 thunk 结束,但尚未调度操作。不过,正如您在我的用法中看到的那样,我需要修改状态才能相应地执行其余代码。

actions/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
}

reducers/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 被发送到 store 时,它​​会使用新的 props 自动更新 UI 的状态。

您可以在 reducer signUpSuccess 中添加一个标志,类似于 isLoggingIn 标志,而不是观察调度的 Action ,并监听 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);

关于javascript - Redux thunk : wait for async function to dispatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56015417/

相关文章:

javascript - 如何使用 javascript 或 jquery 将整个 html 页面转换为 pdf

javascript - 语法错误: Unexpected token { when loading node module during jest test

javascript - useCallback Hooks 获取旧状态值而不更新

javascript - 我如何在 React 中使用钩子(Hook)预初始化状态?

javascript - 在 jquery click 函数中创建对象实例

javascript - 对于每种输入类型,使用 javascript 获取值

javascript - 无法从 jsPDF fromHTML 进行 AJAX 调用

reactjs - 为什么我必须将 babel-presets 放入 .babelrc 和 webpack.config.js 中?

javascript - 如何在 Json-server 和 Axios 中使用 delete 方法?

javascript - React.Children.only expected 在使用 Ref 时收到单个 React 元素子错误