i18next / react-i18next

Internationalization for react done right. Using the i18next i18n ecosystem.
https://react.i18next.com
MIT License
9.29k stars 1.03k forks source link

function t() { [native code] } #1675

Open cosoc opened 1 year ago

cosoc commented 1 year ago

🐛 Bug Report

Display abnormalities may occur when loading the cut flower page for the first time or refreshing it multiple times.

console pringt Warning:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

UI Display Error image

code

I18NExtManage.tsx

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import { resources } from './I18NResources';

i18n
    .use(initReactI18next)
    .init({
        resources,
        fallbackLng: ["en_US","zh_CN","en_GB"],
        ns: ['global', 'dynamics',],
        defaultNS: 'global',
        lng: "en_US",
        debug: false,
        returnNull: false,
        returnEmptyString: true,
        interpolation: {
            escapeValue: false,
        },
        react:{
            bindI18n:'added removed languageChanged loaded',
            bindI18nStore: 'added removed languageChanged loaded',
            nsMode: 'default'
        }
    });
export default i18n;

I18NResources.ts

import { zhCNGlobal } from '../lang/zh_CN/global'
import { enUSGlobal } from '../lang/en_US/global'
import i18n from './I18NExtManage';

export const resources = {
    "en_US": {
        global: enUSGlobal
    },
    "zh_CN": {
        global: zhCNGlobal
    }
}

export const setResources = (resources:any) =>  {
    for (let key in resources) {                
        i18n.addResources(key,"dynamics",resources[key]);
    }
}

Call functions

  ...
    return (
        <div>
            {t('global:MY.KEY')?.toString() }
        </div>

    );

Error if not adding toString function

Occasionally report an error

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

I ensure that the returned value must be a string

export const setResources = (resources:any) =>  {
    for (let key in resources) {                
        i18n.addResources(key,"dynamics",resources[key]);
    }
}

I guess the exception is caused when the page calls the following function, but the added event has been added and re-rendered, but it still doesn't work.

Expected behavior

Regardless of the first load or page switching, refreshing, resource addition, the page displays normally

Environment

runtime version*: i.e. node v18.17.1

adrai commented 1 year ago

please provide a minimal reproducible example repository or codesandbox... I suspect, this happens, bacause you're lazy loading with addResources, and the you may call the t function with a key that is not yet loaded

cosoc commented 1 year ago

please provide a minimal reproducible example repository or codesandbox... I suspect, this happens, bacause you're lazy loading with addResources, and the you may call the t function with a key that is not yet loaded

I modified the logic cut-in timing of dynamically adding resources, and it has returned to normal.

cosoc commented 1 year ago

There is still a problem, your words reminded me that I did use lazy loading for routing. Remember, after using it, my i18n is not working properly! I organized a small demo but couldn't reproduce my anomalies.

cosoc commented 1 year ago

If there is no initialization, why is partial translation possible! image Clicking on this component can control the display and hiding of another display component. When repeatedly clicked, organizational requests will appear, and then clicking again will restore normal operation

cosoc commented 1 year ago

I was sure it was an encapsulation problem with react-i18nex. When I directly removed react-i18nex and used the original i18nex library to implement the page re-rendering logic, all the problems were solved.

When a component is repeatedly added and deleted, react-i18next will have the above problems. It may be that the library performs repeated rendering, or it may be caused by some problem. The problem is currently unknown.

jamesrwaugh commented 1 year ago

Screenshot from 2023-09-25 21-25-30

I'm also running into this. I am not explicitly calling addResources anywhere in the app . How can I make sure everything is first loaded, as @adrai suggests? I am using a custom driver with Tauri, that uses built-in functionality there to load the translations.

export const TauriBackend: BackendModule = {
  type: "backend",
  init: function (
    services: Services,
    backendOptions: object,
    i18nextOptions: InitOptions<object>
  ): void {
    // Nothing to do
  },
  read: function (
    language: string,
    namespace: string,
    callback: ReadCallback
  ): void {
    console.log("i18n", language, namespace);
    invoke<string>("read_translations", {
      language: language,
      namespace: namespace,
    })
      .then((fileContent) => {
        const data = JSON.parse(fileContent);
        callback(null, data);
      })
      .catch((ex) => callback(ex, null));
  },
};
adrai commented 1 year ago

use Suspense or check the ready flag: https://react.i18next.com/latest/usetranslation-hook#not-using-suspense

cosoc commented 1 year ago

使用 Suspense 或检查就绪标志:https://react.i18next.com/latest/usetranslation-hook#not-using-suspense

ready para I tried, but it was still a mistake

cosoc commented 1 year ago

截图自 2023-09-25 21-25-30

我也遇到了这个问题。我没有明确调用addResources应用程序中的任何位置。 我如何确保首先加载所有内容,如@adrai建议? 我正在使用 Tauri 的自定义驱动程序,它使用内置功能来加载翻译。

export const TauriBackend: BackendModule = {
  type: "backend",
  init: function (
    services: Services,
    backendOptions: object,
    i18nextOptions: InitOptions<object>
  ): void {
    // Nothing to do
  },
  read: function (
    language: string,
    namespace: string,
    callback: ReadCallback
  ): void {
    console.log("i18n", language, namespace);
    invoke<string>("read_translations", {
      language: language,
      namespace: namespace,
    })
      .then((fileContent) => {
        const data = JSON.parse(fileContent);
        callback(null, data);
      })
      .catch((ex) => callback(ex, null));
  },
};

I also encountered a problem with the tauri program. Currently, I am using the native i18next to temporarily solve the problem. I do not know what is causing this situation in the react-i8next library.

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

odeyal0 commented 9 months ago

Similar problem in safari (verison in console) image

Simple example: https://codesandbox.io/p/devbox/i18-next-native-function-bug-2srdcz

adrai commented 9 months ago

sorry, but I'm not able to reproduce the issue with your codesandbox example

image
odeyal0 commented 9 months ago

Looks like this issue libwebkit2gtk-4.0-37=2.40.5-1 only... (maybe some another versions) Newer libwebkit2gtk has no this problem.

Reproducing issue on debian-11.7.0: run sudo apt install libwebkit2gtk-4.0-37=2.40.5-1~bed11u1 libjavascriptcoregtk-4.0-18=2.40.5-1~deb11u1 and open _usr/lib/x8664-linux-gnu/webit2gtk-4.0/MiniBrowser and test my sandbox

libwebkit2gtk-4.0-37=2.40.5-1 is latest for some OS like AstraLinux and it's needed for tauri apps.

And if you open devtools on test issue will not be reproducing)

odeyal0 commented 9 months ago

Btw, temporary fix (useTranslation wrapper, 'static' and 'backend' - my namespaces):

import { useMemo } from 'react';
import type { FallbackNs, UseTranslationOptions } from 'react-i18next';
import { useTranslation as useTranslationi18Next } from 'react-i18next';

import type { KeyPrefix, TFunction } from 'i18next';
import type { $Tuple } from 'react-i18next/helpers';

export const useTranslation: typeof useTranslationi18Next = <
  Ns extends
    | 'static'
    | 'backend'
    | $Tuple<'static' | 'backend'>
    | undefined = undefined,
  KPrefix extends KeyPrefix<FallbackNs<Ns>> = undefined,
>(
  ns?: Ns,
  options?: UseTranslationOptions<KPrefix>,
) => {
  const { t: tI18Next, ...other } = useTranslationi18Next<Ns, KPrefix>(
    ns,
    options,
  );

  const t = useMemo<TFunction<FallbackNs<Ns>>>(() => {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const t = (...args: any) => {
      const res = tI18Next(...args);

      return typeof res === 'function' ? res.call(null, ...args) : res;
    };
    t.$TFunctionBrand = tI18Next.$TFunctionBrand;

    return t;
  }, [tI18Next]);

  return { t, ...other };
};