You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ant Design Pro中routes.ts里Day.js日期不更新问题求助

问题:Docker部署后路由跳转URL中的日期固定为部署当日

问题描述

在routes.ts中使用day.js将当前日期拼接至URL,通过Docker容器部署应用后,部署当日day.js能正确显示当前日期,但次日及之后打开应用时,URL中的日期始终为部署当日的日期。例如2024-01-20部署,2024-01-21至2024-01-25打开应用,URL日期始终是2024-01-20。

已尝试的解决方法

  • 修改routes.ts中的日期格式化代码,尝试dayjs().utc().format("YYYY-MM-DD")或dayjs.utc().format("YYYY-MM-DD")
  • 将config/config.ts中的hash从false改为true(history模式仍为{ type: 'hash' })
  • 替换day.js为momentjs

当前配置

/config/config.ts

...

export default defineConfig({
...
hash: true,
history: { type: 'hash' },
...
});

/config/routes.ts

...

export default [
  { path: '/master', component: './master', menuRender: false, },
  {
    name: 'dashboard', icon: 'dashboard', path: '/dashboard',
    routes: [
      {
        path: '/dashboard',
        redirect: `/dashboard/${dayjs().format('YYYY-MM-DD')}`,
      },
      { path: '/dashboard/:date', component: './dashboard', },
    ],
  },
  RecapRoutes,
  AnalysisRoutes,
  DetailRoutes,
  {
    path: '/',
    redirect: `/dashboard/${dayjs().format('YYYY-MM-DD')}`,
  },
  ...
];

解决方案

问题核心在于静态路由配置中的redirect是在构建阶段(部署时)计算的,不是客户端访问时动态计算的。部署时dayjs().format()会被执行一次并固化到打包后的代码中,所以后续用户访问时只会使用部署当日的日期。

方法1:使用路由导航守卫

在应用入口(如src/app.ts或路由配置文件中)添加全局前置守卫,处理根路径和/dashboard的跳转:

import dayjs from 'dayjs';
import type { Router } from 'umi';

export function routerBeforeChange({ history, pathname }: { history: any, pathname: string }) {
  const today = dayjs().format('YYYY-MM-DD');
  // 处理根路径跳转
  if (pathname === '/') {
    history.replace(`/dashboard/${today}`);
    return false; // 阻止默认跳转
  }
  // 处理/dashboard跳转
  if (pathname === '/dashboard') {
    history.replace(`/dashboard/${today}`);
    return false;
  }
}

方法2:修改路由配置为动态redirect(框架支持时)

如果使用的框架(如Umi 3+)支持动态redirect函数,可将路由中的redirect改为函数形式,运行时计算:

// routes.ts中修改对应的路由项
{
  path: '/dashboard',
  redirect: () => `/dashboard/${dayjs().format('YYYY-MM-DD')}`,
},
{
  path: '/',
  redirect: () => `/dashboard/${dayjs().format('YYYY-MM-DD')}`,
},

方法3:组件内部处理跳转

在根组件或/dashboard对应的组件中,通过生命周期钩子动态处理跳转:

// dashboard组件示例
import { useEffect } from 'react';
import { useHistory, useLocation } from 'umi';
import dayjs from 'dayjs';

export default function Dashboard() {
  const history = useHistory();
  const location = useLocation();

  useEffect(() => {
    if (location.pathname === '/dashboard') {
      const today = dayjs().format('YYYY-MM-DD');
      history.replace(`/dashboard/${today}`);
    }
  }, [history, location]);

  // 组件其他逻辑...
}

补充说明

  • 时区问题:若需确保日期对应特定时区,可引入dayjs的时区插件(dayjs-plugin-timezone),配置时区后再格式化日期。
  • 验证:修改后重新构建镜像并部署,次日访问即可看到URL中的日期为当日日期。

内容的提问来源于stack exchange,提问作者Decki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 16:01:27