如果后端加载失败,react-i18n useSuspense 永远不会结束

react-i18n useSuspense never ends if backend loading fails

在我的 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 回退组件或重定向到任何错误页面。

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

仅供参考:将事件侦听器放入内部不是一个好主意

顺便说一句:为什么要在未加载翻译时显示错误?为什么不显示后备文本?该错误无论如何都不适用于最终用户...