gpt4 book ai didi

javascript - React.suspense "handle"i18next 后端如何加载?

转载 作者:行者123 更新时间:2023-12-05 04:45:44 26 4
gpt4 key购买 nike

我正在使用一些非常标准的 create-react-app 样板,它使用延迟加载和 react-i18next 作为翻译库。该库使用 i18next-http-backend 从远程 API 获取翻译文件。

我想了解的是,React.suspense 究竟是如何能够“识别”这个异步调用,并在它完成之前显示回退 UI。

Index.ts 文件:

import "./i18n";//Notice this

const container = document.getElementById("root");
ReactDOM.render(
<StylesProvider jss={jss}>
<ThemeProvider theme={theme}>
<React.StrictMode>
<BrowserRouter>
<Router />
</BrowserRouter>
</React.StrictMode>
</ThemeProvider>
</StylesProvider>,
container
);

国际化文件:

i18n
.use(Backend)
.init({
backend:{
loadPath: 'https://someRemoteApi/dictionary',
})

路由器:

const Home = lazy(() => import("../../modules/home/Home"));
const Router: React.FC = (props) => {
return (
<>
<ErrorBoundary>
<Suspense fallback={<div className={styles.loader}><Loader /></div>}>
<Switch>
<ProtectedRoute exact component={Home} path="/"/>
...more routes
</Suspense>
</ErrorBoundary>
</>
);
};

使用此设置,令我惊讶的是,回退会呈现在屏幕上,直到此后端插件完成其工作。我正在尝试了解它的机制,以及是否可以将其用于其他异步操作

React 文档明确指出:

React.Suspense lets you specify the loading indicator in case somecomponents in the tree below it are not yet ready to render. Today,lazy loading components is the only use case supported by<React.Suspense>:

如有任何澄清,我们将不胜感激。

最佳答案

Suspense 的想法是当一个组件抛出一个 Promise(或在组件渲染期间调用的任何东西)时,React 寻找最接近的 Suspense 以显示后备 UI。

在您的情况下,您的组件正在使用 useTranslate Hook 。当 namespaces 尚未加载时,它会抛出一个 Promise 并加载 namespaces。在渲染阶段,React 捕获抛出的 Promise 并在树上寻找最接近的 Suspense 组件以显示回退 UI。

这是钩子(Hook) useTranslation 的片段:

 // not yet loaded namespaces -> load them -> and trigger suspense
throw new Promise((resolve) => {
loadNamespaces(i18n, namespaces, () => {
resolve();
});
});

您可以从 here 查看钩子(Hook) useTranslation 是如何工作的

关于javascript - React.suspense "handle"i18next 后端如何加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69066146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com