来自 "react-i18next" 库的 { useTranslation } 输出错误

{ useTranslation } from "react-i18next" library outputs error

我有以下代码:

import React, { Suspense } from "react";
import { useTranslation } from "react-i18next";
import "../i18n";
const Loader = () => {
  return (
    <div>
      <h3>loading...</h3>
    </div>
  );
};
export default props => {
  const { t } = useTranslation(); //the problem is in this line

  return (
    <Suspense fallback={<Loader />}>
        <h1>{t("testTitle")}</h1>
    </Suspense>
  );
};

但是没用。相反,红色屏幕显示以下文本:A React 组件在渲染时暂停,但未指定回退 UI。在树的较高位置添加组件以提供加载指示器或占位符以显示

一开始,我认为问题出在 <Suspense fallback={<Loader/>}> 行,但经过几次尝试后,我发现它实际上来自 useTranslation() 行。

我该如何解决这个问题?

我找到了导致问题的原因:虽然 useTranslation() 行在默认组件内,但不在 <Suspense fallback={<Loader />}> 范围内。所以解决方案是不导出该组件。相反,您必须将它分配给一个变量,然后创建一个包装它的新组件:

import React, { Suspense } from "react";
import { useTranslation } from "react-i18next";
import "../i18n";
const Loader = () => {
  return (
    <div>
      <h3>loading...</h3>
    </div>
  );
};
const FirstComponent = props => { //You assign it into a varible instead of exporting directly

  const { t } = useTranslation(); 

  return (
    <Suspense fallback={<Loader />}>
        <h1>{t("testTitle")}</h1>
    </Suspense>
  );
};

export default props => { //This is the component that you have to export instead

  return (
    <Suspense fallback={<Loader />}>
        <FirstComponent/>
    </Suspense>
  );
};