首页 > 解决方案 > 使用 Spring Boot 响应延迟加载数据

问题描述

我的解决方案基于前端应用 React 、 redux 和 material-u 以及后端 Springboot 应用。

我有一个从数据库中获取大量记录的 Rest API。这会在 UI 上造成延迟,我想防止这种情况发生。

表格组件:

export default function Export(props) {
  return (
   <div>
  <MaterialTable
    title={<Typography variant="h6">{}</Typography>}
    data={props.data}
    options={{
      pageSize: 50,
      pageSizeOptions: [50, 100, 150],
      search: true,
      sorting: false,
      headerStyle: {
        fontWeight: "bold",
        padding: "4px",
      },
    }}
  ></MaterialTable>
</div>
 );
}


export const getExportByLastModifiedDate = (lastModifiedDate) => {
 return async (dispatch) => {
   dispatch({ type: EXPORT_BY_LASTMODIFEDDATE_START });
   await axios({
      method: "get",
      url: "/api/export?lastModifiedDate=" + lastModifiedDate,
  })
  .then(function(response) {
    dispatch({
      type: EXPORT_BY_LASTMODIFEDDATE_SUCCESS,
      payload: response.data,
    });
  })
  .catch(function(error) {
    dispatch({ type: EXPORT_BY_LASTMODIFEDDATE_ERROR, payload: error });
  });
 };
};

后端 API:

@GetMapping("/export")
public ResponseEntity<List<ExportDto>> getExportByLastModifiedDate(@RequestParam(value = "lastModifiedDate", required = true) String lastModifiedDate) {
    
    Optional<List<ExportDto>> optional = Optional.ofNullable(service.getExportByLastModifiedDate(lastModifiedDate));
    return optional.map(response -> ResponseEntity.ok().body(response)).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}

我想要做的是获取前 1000 条记录并将它们呈现到 UI,而在后端该过程将继续。

我怎样才能做到这一点 ?

谢谢

标签: javascriptreactjsspring-bootasync-awaitmaterial-table

解决方案


一种可能的解决方案可能是在您的query和中添加分页支持backend rest api。例如,首先使用 调用后端page=0&pageSize=1000,这将返回前 1000 条记录,加载此记录后,您将使用 调用后端page=1&pageSize=1000,这将返回接下来的 1000 条记录。

如果您使用spring data jpa. 如果您使用native querythen,大多数数据库都有支持这种分页的语法,您需要修改查询以进行分页。


推荐阅读