插件窝 干货文章 Umi后台页面跳转如何保持语言参数不变?

Umi后台页面跳转如何保持语言参数不变?

参数 语言 history 使用 970    来源:    2025-03-23

在使用 Umi 框架开发后台页面时,如果你希望在页面跳转时保持语言参数不变,可以通过以下几种方式实现:

1. 使用 history.pushhistory.replace 时手动携带语言参数

在 Umi 中,你可以使用 history.pushhistory.replace 进行页面跳转。为了保持语言参数不变,你可以在跳转时手动将当前的语言参数添加到新的 URL 中。

import { history } from 'umi';

// 获取当前的语言参数
const currentLanguage = window.location.search.match(/locale=([^&]*)/)?.[1] || 'zh-CN';

// 跳转时携带语言参数
history.push(`/your-target-page?locale=${currentLanguage}`);

2. 使用 useLocationuseHistory Hooks

如果你在 React 组件中使用 Hooks,可以使用 useLocationuseHistory 来获取当前的语言参数,并在跳转时携带该参数。

import { useLocation, useHistory } from 'umi';

function YourComponent() {
  const location = useLocation();
  const history = useHistory();

  // 获取当前的语言参数
  const currentLanguage = new URLSearchParams(location.search).get('locale') || 'zh-CN';

  const handleNavigate = () => {
    // 跳转时携带语言参数
    history.push(`/your-target-page?locale=${currentLanguage}`);
  };

  return (
    <button onClick={handleNavigate}>Go to Target Page</button>
  );
}

3. 使用 umi-plugin-locale 插件

如果你使用了 umi-plugin-locale 插件来管理多语言,Umi 会自动处理语言参数的传递。你只需要确保在跳转时使用 history.pushLink 组件,Umi 会自动将当前的语言参数附加到 URL 中。

import { history } from 'umi';

// 跳转时无需手动携带语言参数,umi-plugin-locale 会自动处理
history.push('/your-target-page');

4. 使用 Link 组件

如果你在 React 组件中使用 Link 组件进行页面跳转,Umi 会自动处理语言参数的传递。

import { Link } from 'umi';

function YourComponent() {
  return (
    <Link to="/your-target-page">Go to Target Page</Link>
  );
}

5. 全局处理语言参数

如果你希望在整个应用中自动处理语言参数,可以在 src/app.tsxsrc/global.ts 中全局处理语言参数的传递。

import { history } from 'umi';

// 在全局拦截器中处理语言参数
history.listen((location) => {
  const currentLanguage = new URLSearchParams(location.search).get('locale') || 'zh-CN';
  // 在每次跳转时自动携带语言参数
  if (!location.search.includes('locale=')) {
    history.replace(`${location.pathname}?locale=${currentLanguage}`);
  }
});

总结

通过以上几种方式,你可以在 Umi 后台页面跳转时保持语言参数不变。具体选择哪种方式取决于你的项目需求和代码结构。如果你使用了 umi-plugin-locale 插件,推荐使用自动处理的方式,这样可以减少手动管理语言参数的工作量。