当应用程序外部的 DB 上的数据发生更改时,如何刷新 React Redux 应用程序 [英] How to refresh a react redux application when data changes on DB outside of the application

查看:51
本文介绍了当应用程序外部的 DB 上的数据发生更改时,如何刷新 React Redux 应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景 - 数据库中某些表的数据发生更改,例如使用来自另一个进程的文件上传,例如不属于 react-redux 应用程序的 ETL 工具.那么我们如何刷新 react-redux 应用程序组件呢?网络套接字是唯一将这种变化从服务器推送到客户端的吗?或者我们是否定期刷新受影响的组件?但是所有这些端口都必须一直保持打开状态吗?后端是一个 java/oracle 应用程序.谢谢

Scenario - data changes on some of the tables in the database, say using a file upload from another process, like an ETL tool that is not part of the react-redux application. How can we then refresh the react-redux application components? Is web sockets the only to push such a change from server to client? Or do we refresh the affected components at regular intervals? but then all such ports will have to be left open all the time? Backend is a java/oracle application. Thanks

推荐答案

您应该进行 Ajax 调用(我喜欢使用 axios) 到数据库每次相关的 React 组件加载时,以确保数据是最新的.如果您使用 React.createClass 创建组件,请在该组件内使用 getInitialState().

You should make an Ajax call (I like using axios) to the database every time the relevant React component loads to ensure that the data is up to date. If you are creating the component with React.createClass, use getInitialState() inside said component.

由于您不希望组件在每次加载时查询数据库,而是只在指定的时间段后查询,我建议对以下代码进行修改:

Since you don't want the component to query the DB every time it loads but rather only after a specified time period, I suggest a variation on the code below:

getInitialState() {
  //Define a variable and set as the current date object
  let date = new Date;

  //Convert the variable's value to a string
  date = date.toString();

  //Slice the day of the month from the date string
  let day = date.slice(6,8);

  //Query the database if it's the 15th or 28th (approximately every 2 
  //weeks, accounting for February
  if (day == ("15" || "28")) {
    //Ajax call here
    return {data: ajaxResponse};
  }
}

请注意,每次组件在所选日期加载时,此代码都会查询数据库.由于日期对象下降到毫秒,您可以根据需要缩小时间窗口.请记住,如果在此期间从未加载组件,则在再次满足 if 条件之前不会查询数据库.

Please note that this code will query the DB every time the component loads on the days selected. Since the date object goes down to the millisecond, you could make the time window as narrow as you want. Just keep in mind that if the component is never loaded during that time, the DB will not be queried until the if conditional is satisfied again.

这篇关于当应用程序外部的 DB 上的数据发生更改时,如何刷新 React Redux 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆