简体   繁体   English

React 中的多个 Suspense 声明

[英]Multiple Suspense declaration in React

For example I have this declaration:例如我有这个声明:

Scenario 1:场景一:

const ComponentA = lazy(() => import('pages/ComponentA'));
const ComponentB = lazy(() => import('pages/ComponentB'));

<Router>
  <Switch>
     <Suspense fallback={'loading...'}>
       <Route path="/A" component={ComponentA} exact/>
       <Route path="/B" component={ComponentB} exact/> 
     </Suspense>
  </Switch>
</Router>

This scenario is fine if the loading dependency of ComponentA is just 1.如果ComponentA的加载依赖关系仅为 1,则此场景很好。

But for Scenario 2: what if I have multiple dependency in ComponentA ?但是对于场景 2:如果我在ComponentA中有多个依赖项怎么办?

Code 2代码 2

import Dependency1 from 'component/dependency1';
import Dependency2 from 'component/dependency2';

const ComponentA = () => {
   return (
     <div>
       <Dependency1/>
       <Dependency2/>
     </div>
   );
}

is it okay to separate the Suspense declaration for each Dependency?可以将每个依赖项的 Suspense 声明分开吗? like this:像这样:

Code 3代码 3

 const Dependency1 = lazy(() => import('component/dependency1'));
 const Dependency2 = lazy(() => import('component/dependency2'));

 const ComponentA = () => {
   return (
     <div>
       <Suspense fallback={'Loading Dependency1'}>
         <Dependency1/>
       <Suspense/>
       <Suspense fallback={'Loading Dependency2'}>
        <Dependency2/>
       <Suspense/>
     </div>
   );
}

then I'll remove the Suspense declaration in the Router file...然后我将删除路由器文件中的 Suspense 声明...

My Question is it okay to have a structure like Code 3 since I want to have a multiple separate loading indicator in each dependency?我的问题是可以有像代码 3这样的结构,因为我想在每个依赖项中有多个单独的加载指示器?

Is there any downside of this approach like performance or multiple request in each sub-component since I'm code splitting each Dependency?由于我正在对每个依赖项进行代码拆分,因此这种方法是否有任何缺点,例如每个子组件中的性能或多个请求?

Sure, this approach is totally fine, especially when you want to have different loaders for different components.当然,这种方法完全没问题,尤其是当你想为不同的组件使用不同的加载器时。

There is small downside you mentioned, multiple request for each lazy component, but it would not matter too much.您提到的一个小缺点是,每个惰性组件都有多个请求,但这并不重要。 If some components are conditional it would even be better to use multiple loaders since some users might not even need Dependency2 at all, for example.例如,如果某些组件是有条件的,那么使用多个加载器会更好,因为某些用户甚至可能根本不需要Dependency2

One thing to consider is "loaders clutter".要考虑的一件事是“装载机混乱”。 It might be better from UX perspective to have skeleton page instead of 4-5 different loaders which are going to load separately and page might even jump unexpectedly.从 UX 的角度来看,最好有骨架页面,而不是 4-5 个不同的加载器,它们将分别加载,页面甚至可能会意外跳转。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM