【问题标题】:{ useTranslation } from "react-i18next" library outputs error{ useTranslation } 来自“react-i18next”库输出错误
【发布时间】:2019-09-04 04:30:51
【问题描述】:

我有以下代码:

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>
  );
};

但它不起作用。相反,会出现一个带有以下文本的红色屏幕:渲染时暂停的 React 组件,但未指定备用 UI。在树的较高位置添加一个组件以提供加载指示器或占位符来显示

一开始,我以为问题出在&lt;Suspense fallback={&lt;Loader/&gt;}&gt; 行,但经过几次尝试后,我发现问题实际上出在useTranslation() 行。

我该如何解决这个问题?

【问题讨论】:

    标签: reactjs i18next react-i18next


    【解决方案1】:

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

    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>
      );
    };
    

    【讨论】:

    • 我相信只在&lt;Suspense&gt; 组件下允许调用useTranslation(如果启用了悬念)。
    猜你喜欢
    • 2021-10-30
    • 2019-08-06
    • 2023-02-23
    • 2020-10-07
    • 2021-07-02
    • 2020-04-11
    • 2022-07-06
    • 2020-12-25
    • 2020-08-05
    相关资源
    最近更新 更多