reactjs - React/Redux/Backend 设置以获得实时增量进度
问题描述
假设我有提交表单的 React/Redux 前端。
收到表单后,我的后端部分将依次对十个文件执行脚本。我想在发生这种情况时在前端显示增量进度(即当前完成的文件数)。
这个问题的OP设置了一个reducer,将状态更新为一个数字。我们将如何与后端集成?可以不使用套接字吗?
解决方案
我认为最好的方法是使用 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
}
}
推荐阅读
- sql - 用于列出用户、角色并将用户添加到 Azure SQL DB 的 PowerShell 脚本
- ansible - 为什么将“ansible_python_interpreter”配置选项设置为“/usr/bin/python3”
- google-maps - 创建结算帐户是否会向我收费?
- java - 实现工厂模式
- python - docker-compose exec 导致 [Errno 2] No such file or directory: 'docker-compose': 'docker-compose' in docker container
- javascript - 如何为用户选择的输入(复选框)值使用本地存储。需要使用纯 JavaScript(无 Jquery)
- spring - 使用 Schedulers.elastic 进行 Spring 集成测试
- sql - 从每个组中检索列的最后一个元素,并将其用作下一组中同一列的第一个元素
- r - 强制 updateSelectizeInput 在更改事件上触发
- java - 使用带有 jdbc 驱动程序的 mysql 函数 select now()