【问题标题】:react-i18next - detecting if fallback language was usedreact-i18next - 检测是否使用了后备语言
【发布时间】:2020-03-02 15:56:04
【问题描述】:

我正在开发组件来跟踪丢失的翻译,我的目标是使用样式化的组件来设置丢失的翻译的样式,但是我无法找到一种方法来检测 t("someKey") 是否从当前设置的语言返回翻译值,或者如果它丢失则默认回退.有任何想法吗?文档在这一点上没有帮助。

【问题讨论】:

  • 好问题。我也想就这个主题发表一些意见!
  • i18next 中似乎有选项直接:https://www.i18next.com/overview/configuration-options#missing-keys。尚未测试,但我们也许可以创建一个缺少的密钥处理程序,它只是调用 Sentry 的副作用。虽然不确定它的后果(我仍然想使用后备语言,但也会在发生这种情况时告诉 Sentry)

标签: react-i18next


【解决方案1】:

我们的团队部分解决了它(编辑:至少对于完全丢失的令牌,当它使用后备语言时还没有)。配置其实在i18next级别,见:https://www.i18next.com/overview/configuration-options

这是使用next-i18next 时的解决方案(我写这篇文章时是v8)。请注意,在这种情况下,您需要 i18n 配置可序列化 (https://github.com/isaachinman/next-i18next#unserialisable-configs)。

此函数预计在客户端运行,因此您可以使用@sentry/browser

// NOTE: next-i18next.config.js is a JS file, so no TypeScript here
const Sentry = require("@sentry/browser");

module.exports = {
  // @see https://www.i18next.com/overview/configuration-options
  i18n: {
    defaultLocale: "en",
    locales: ["en", "fr", "de", "tr"],
    localeDetection: false, 
    // Set to true to enable the missingKeyHandler callback
    saveMissing: true,
    // Method triggered client-side when a token is missing
    // It will still respect your fallback language, 
    // but let you add a side-effect like calling Sentry
    missingKeyHandler: (
      ngs,
      ns,
      key,
      fallbackValue,
      updateMissing,
      options
    ) => {
      Sentry.captureException(new Error("Missing i18n key"), {
        extra: { ngs, ns, key, fallbackValue, updateMissing, options },
      });
    },

【讨论】:

    【解决方案2】:

    我对此真的很缺乏经验,所以到目前为止我发现的唯一解决方案是禁用回退并浏览页面。调试器会告诉你错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-24
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多