V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
noobma
V2EX  ›  程序员

umijs ssr 渲染时,怎么把国际化 locale 传递到非组件函数中使用(如一些 util 函数)

  •  
  •   noobma · 2021-10-12 18:12:25 +08:00 · 455 次点击
    这是一个创建于 898 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在 node 端通过解析路径(/zh/news 、/en/news)拿到 zh 、en 等 locale,通过 umijs 提供的 render 可以把 locale 传递到页面的 props 中,可是我在组件外的一些地方如何拿到这个 locale 呢,比如有个公共的 request 函数,在这个函数里我要把 header 中的 accept-language 设置成对应的 locale 。

    export function request(params {
      const headers = {
        'Accept-Language': '这里如何取到 locale???'
      };
      // ...
    }
    

    在 umijs ssr 的文档里有这样的代码,是把 locale 挂到 nodejs 的 global 上,可是这样多个请求一起过来的时候,很大可能会出现 locale 污染的情况啊。

    // app.ts
    export const ssr = {
      beforeRenderServer: async ({
        env,
        location,
        history,
        mode,
        context,
      }) => {
        // global 为 Node.js 下的全局变量
        // 避免直接 mock location,这样会造成一些环境判断失效
        global.mockLocation = location;
    
        // 国际化
        if (location.pathname.indexOf('zh-CN') > -1) {
          global.locale = 'zh-CN'
        }
      }
    }
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3210 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:00 · PVG 20:00 · LAX 05:00 · JFK 08:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.