我尝试安装react-i18next并按照官方文档进行操作。有一点,它说在index.js文件中导入i18n.js。
import './i18n'
但是,在导入 i18n.js 后,我收到以下错误并且所有页面都崩溃了:
Uncaught Error: A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition.
我尝试检查完整的文档,但没有找到问题的任何解决方案,也没有找到任何提及可能导致此错误的内容。
我在这里做了很多假设,因为这个问题的背景很少,但考虑到我只是花了一整天的时间从相反的方向工作,我想我会分享,以防你的问题类似。
如果您通过 i18n 文档遵循实现,您的 i18n 文件看起来像这样
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import resourcesToBackend from 'i18next-resources-to-backend';
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.use(resourcesToBackend((language, namespace) => import(`./public/locales/${language}/${namespace}.json`)))
.init({
lng: "en-US", // if you're using a language detector, do not define the lng option
fallbackLng: ["en-US", "en", "fr"],
interpolation: {
escapeValue: false // react already safes from xss => https://www.i18next.com/translation-function/interpolation#unescape
}
});
export default i18n;
大多数情况下都可以正常工作,除非有页面在 i18n 仍在获取其资源时开始尝试渲染和重新渲染。修复很简单,只需等待 i18n 完成即可执行其他操作。
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import resourcesToBackend from 'i18next-resources-to-backend';
const languageInit = i18n
.use(initReactI18next) // passes i18n down to react-i18next
.use(resourcesToBackend((language, namespace) => import(`./public/locales/${language}/${namespace}.json`)))
.init({
lng: "en-US", // if you're using a language detector, do not define the lng option
fallbackLng: ["en-US", "en", "fr"],
interpolation: {
escapeValue: false // react already safes from xss => https://www.i18next.com/translation-function/interpolation#unescape
}
});
export default languageInit;
现在无论您导入何处,都可以将其包装起来。
languageInit.then(()=>{
root.render(
<React.StrictMode>
<Provider store={store}>
<PersistGate loading={<Loading />} persistor={persistor}>
<Router/>
</PersistGate>
</Provider>
</React.StrictMode>
);
})