【问题标题】:How to perform dependent async calls in redux?如何在 redux 中执行依赖异步调用?
【发布时间】:2021-03-19 09:30:03
【问题描述】:

背景

我有使用 redux 和 redux-thunk 的 react 应用程序。

试图了解如何编排异步调用。仅在先前已分派的操作(API 调用)成功时如何分派操作。

用例

我有EmployeesComponent。该组件有两个虚拟的表示组件

  • EmployeesList 基本上列出了员工。
  • AddEmployeeForm 是一种用于添加新员工的模式。

在渲染EmployeesComponent 时,在useEffect 挂钩中,我调度了一个动作来加载员工。到目前为止,一切顺利。

当我用户在AddEmployeeForm中输入数据并提交表单时,如果API调用成功,我想再次实现加载所有员工。

我无法理解如何知道我是否可以分派操作以加载所有员工。这是我的提交处理程序的样子。

   const handleSubmit = async (e) => {
        e.preventDefault();
    
        console.log("Handle submit add new employee..");
    
        const employeeData = inputs;
        // Validate data from the AddEmployeeForm
        // in case of validation errors, abort



       dispatch(addEmployee(employeeData)); // calls API to save the data

       // How to await the result of the dispatched action (addEmployee) before continuing? 

       // If addEmployee was not successful abort
       // The error data from the API call is saved in the redux store, 
       // so the UI gets notified and can display it properly

        // If addEmployee was successful, I want to
        clearForm(); // local state from the component
        handleCloseForm(); // local state from the component

        dispatch(loadEmployees());
      };

挑战

handleSubmit 中的当前方法对我来说很奇怪。业务逻辑有点放在 UI 中,并且失去了将 UI 和业务逻辑明确分离的好处。我很难弄清楚要采用什么方法以及如何处理这些用例。

另一个用例示例:

  • 派遣登录用户
  • 如果登录成功,则从后端获取令牌
  • 如果登录成功,则根据检索到的令牌调度操作以加载用户数据

【问题讨论】:

    标签: redux react-redux redux-thunk redux-async-actions


    【解决方案1】:

    在 Redux 中,async logic is normally written in the form of "thunk" functions。这使您可以提取需要与 React 组件外部的存储交互的逻辑,尤其是需要执行诸如获取数据和分派结果之类的操作的异步逻辑。

    你也可以return a promise from a thunk and await that promise in the component after dispatching

    【讨论】:

    • 谢谢@markerikson 您能否推荐一个模式或教程,说明 UI 应如何订阅异步调用的结果?就像我在状态中声明所有可能的事件一样吗?像“employeeCreatedStatus”然后有一个为该事件设置状态的减速器?或者基于上面的示例,UI 应该如何知道可以执行 clearForm() 和 handleCloseForm() ?编辑:没有正确阅读异步 thunk 并等待承诺。要去挖掘它。顺便说一下,你能推荐视频吗?
    • 请通读 Redux 核心文档中的 "Redux Essentials""Redux Fundamentals" 教程,其中展示了我们当前推荐的使用 Redux 和处理异步逻辑的模式。
    • 好的,我需要再通读一遍。显然,我忘记了事情和/或没有理解所有内容。谢谢,马克!
    猜你喜欢
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    相关资源
    最近更新 更多