首页 > 解决方案 > React/Redux/Backend 设置以获得实时增量进度

问题描述

假设我有提交表单的 React/Redux 前端。

收到表单后,我的后端部分将依次对十个文件执行脚本。我想在发生这种情况时在前端显示增量进度(即当前完成的文件数)。

这个问题的OP设置了一个reducer,将状态更新为一个数字。我们将如何与后端集成?可以不使用套接字吗?

标签: reactjsredux

解决方案


我认为最好的方法是使用 websocket,后端将发布进度事件,前端甚至订阅该事件。但是,由于您不喜欢使用 websocket,我能想到的唯一方法是使用间隔轮询。

在您的 redux 操作中,您可以执行以下操作:

async doSomething = () => {
   return async (dispatch) => {
       await callApiForStart(); // call your api to start the progressing
       dispatch(startProgressing()); // tell the reducer to update the progressing

       const interval = setInterval(async () => {
          const result = await callApiToCheckProgress(); // in the backend, you can store the progress to somewhere like memory or redis or even DB.
          dispatch(increaseProgress(result)); // tell the reducer to update the progress base on result
          if (result === true) { // any condition to complete the check
              clearInterval(interval);
              dispatch(stopProgressing());
          }
       }, 1000); // my example interval is 1000, should depends on your logic
   }
}

推荐阅读