• 请不要在回答技术问题时复制粘贴 AI 生成的内容
noobma
V2EX  ›  程序员

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

  •  
  •   noobma · Oct 12, 2021 · 976 views
    This topic created in 1701 days ago, the information mentioned may be changed or developed.

    在 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'
        }
      }
    }
    
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5325 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 06:01 · PVG 14:01 · LAX 23:01 · JFK 02:01
    ♥ Do have faith in what you're doing.