1

我有以下代码:

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。在树的较高位置添加一个组件以提供加载指示器或占位符来显示

一开始,我以为问题出<Suspense fallback={<Loader/>}>在线路上,但经过几次尝试后,我喜欢它实际上是为了useTranslation()线路。

我怎样才能解决这个问题?

4

1 回答 1

1

我找到了导致问题的原因:虽然该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>
  );
};
于 2019-09-03T20:30:51.150 回答