繁体   English   中英

什么是最好的方法Redux-thunk异步请求来处理onSuccess和onError?

[英]what will be best Approach for Redux-thunk Async Request to handle onSuccess and onError?

什么应该是管理Redux-Thunk异步请求的最佳方法。 就像我在服务器上发布一些数据一样,连接组件会检查错误

方法1:我只是在我的动作创建者中返回新的Promise来检查解决或拒绝使用then

const update = (todoId, isDone) => (dispatch) =>
new Promise(function(resolve, reject) {
dispatch({
  type: 'SET_SAVING',
  saving: true
});
// Function is expected to return a promise
callUpdateApi(todoId, isDone).then(updatedTodo => {
  dispatch({
    type: 'SET_SAVING',
    saving: false
  });

  resolve(updatedTodo);
}).catch(error => {
  // TBD: Handle errors for Redux

  reject(error);
})
});

方法2:使用dispatch通过if-else条件管理render方法中的错误

const update = (todoId, isDone) => (dispatch) => {
dispatch({
    type: 'SET_SAVING',
    saving: true
  });
  // Function is expected to return a promise
  callUpdateApi(todoId, isDone).then(updatedTodo => {
    dispatch({
      type: 'SET_SAVING',
      saving: false
    });
  });
  // TBD: Handle errors
}

如果我使用Action创建者的“return Promise”或者仅使用调度操作存储错误和成功处理,请帮助我找到最佳解决方案。 因为onsuccess我需要在我的组件中做一些事情并且也出错

const update = (todoId, isDone) => (dispatch) =>
new Promise(function(resolve, reject) {
dispatch({
  type: 'SET_SAVING',
  saving: true
});
// Function is expected to return a promise
callUpdateApi(todoId, isDone).then(updatedTodo => {
  dispatch({
    type: 'SET_SAVING',
    saving: false
  });

  resolve(updatedTodo);
}).catch(error => {
  // TBD: Handle errors for Redux

  reject(error);
})
});

如果您的callUpdateApi返回一个promise,您不必将整个操作包装在一个promise中,只需返回callUpdateApi 至于错误处理,常见的方法是在redux状态的某处设置一个标志以及saving标志,例如知道何时发生错误。 然后,您的组件将接收这些标志并对其执行某些操作

const update = (todoId, isDone) => (dispatch) => {
  dispatch({
    type: 'SET_SAVING',
    saving: true
  });

  return callUpdateToApi(todoId, isDone).then(updatedTodo => {
    dispatch({
      type: 'SET_SAVING',
      saving: false,

      // Do something with your API response
      // e.g. update your redux store via a reducer
      updatedTodo
    });
  })
  .catch(err => {
    // Handle error, for example set a error flag
    // in your redux state so your components know an error occured
     dispatch({
      type: 'SET_SAVING',
      saving: false,
      error: true
    });
  });
}

连接您的组件,以便他们可以访问errorsaving标志,例如在呼叫失败时显示错误:

export default connect(
  state => ({
    error: state.module.error,
    saving: state.module.saving
  })
)(Component);
// Inside your JSX
{this.props.error && <p>An error occured</p>}

我们使用的最佳做法是为每个重击动作分配3个动作:

  1. 行动开始了
  2. 行动成功
  3. 行动失败

callUpdateApi是一个承诺,然后在你的thunk中返回它,如下所示:

const update = (params) => (dispatch) => {
  dispatch(started())
  return callUpdateApi(params)
    .then(result => dispatch(succeeded(result)))
    .catch(error => dispatch(failed(error)))
}

在reducer中,你可以切换saving标志,将其设置为true ,对于成功或失败,将其设置为false

暂无
暂无

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

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