在我的react应用程序中,我使用i18next-http-backend从后端响应加载翻译数据。目前,我的应用程序在以下配置中运行良好:
config.js
import i18n from 'i18next';
import {initReactI18next} from 'react-i18next';
import HttpApi from 'i18next-http-backend';
import axios from "axios";
const backendOptions = {
loadPath: 'http://localhost:3000/messages',
request: async (options, url, payload, callback) => {
try {
const translation = await axios.get(url);
callback(null,{
status: 200,
data: JSON.stringify(translation.data),
});
} catch (e) {
callback(e);
}
},
};
const i18nextOptions = {
debug:true,
backend: backendOptions,
fallbackLng: 'en',
lng: 'en',
load:"languageOnly",
react: {
useSuspense: true,
},
ns: ['translations'],
defaultNS: 'translations'
}
i18n.use(initReactI18next)
.use(HttpApi )
.init(i18nextOptions);
i18n.languages = ['en', 'jp'];
i18n.on('failedLoading', function(lng, ns, msg) {
console.log("backend error");
})
export default i18n;
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import './i18n/config';
import {store} from "./app/store";
import {Provider} from "react-redux";
import {ErrorBoundary} from "react-error-boundary";
import {Suspense} from "react";
import RuntimeErrorPage from "./features/error/runtime-error-page";
import Spinner from "./components/common/Spinner";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<ErrorBoundary FallbackComponent={RuntimeErrorPage}>
<Suspense fallback={<Spinner/>}>
<Provider store={store}>
<App/>
</Provider>
</Suspense>
</ErrorBoundary>
</React.StrictMode>
);<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
然而,如果有任何后端错误,应用程序会卡在Suspense中。如果我禁用悬念,那么i18next将在没有任何资源的情况下初始化。如何处理来自request的任何错误?我需要一种方法来调用ErrorBoundary回退组件或重定向到任何错误页面。
发布于 2022-05-17 11:21:53
i18next从不抛出错误..。
将那些失败的加载保存到其他地方:https://codesandbox.io/s/react-i18next-http-example-forked-9ted7y?file=/src/i18n.js:188-295
然后创建自己的逻辑来显示内容:https://codesandbox.io/s/react-i18next-http-example-forked-9ted7y?file=/src/app.js:155-377
fyi:扔进一个事件侦听器不是个好主意。
顺便问一句:为什么不加载翻译时要显示错误?为什么不显示一个后备文本呢?这个错误不是针对最终用户的.
https://stackoverflow.com/questions/72269318
复制相似问题