最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamic Lazy Loading using React.Lazy (16.6.0) - Stack Overflow

programmeradmin0浏览0评论

I get an array like

{Path:xxx, 
Component:"./xxx/ComPXX"}

from my API and based on that create my application's routes. At the moment I'm using React-Loadable (5.5.0) and React-Router (4.4.0-betax to avoid warnings in strict mode). See working example here.

Since React 16.6 has introduced React.lazy, I'm trying to migrate my solution, however I'm facing errors and difficulties however I try to do this. You can see migrated (failing) code here.

Any Idea why this isn't working? Can it be because React.Lazy doesn't accept variables?

I get an array like

{Path:xxx, 
Component:"./xxx/ComPXX"}

from my API and based on that create my application's routes. At the moment I'm using React-Loadable (5.5.0) and React-Router (4.4.0-betax to avoid warnings in strict mode). See working example here.

Since React 16.6 has introduced React.lazy, I'm trying to migrate my solution, however I'm facing errors and difficulties however I try to do this. You can see migrated (failing) code here.

Any Idea why this isn't working? Can it be because React.Lazy doesn't accept variables?

Share Improve this question edited May 3, 2019 at 14:04 Sagiv b.g 31k10 gold badges72 silver badges104 bronze badges asked Oct 25, 2018 at 10:08 AshaAsha 4,3617 gold badges46 silver badges57 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

You got 2 3 main issues:

  1. In this line:

    var c = <dynamicLoader ponent={prop.ponent} />;
    

    User-Defined Components Must Be Capitalized. so change it to this:

    var c = <DynamicLoader ponent={prop.ponent} />;
    

    Obviously you'll need to change the declaration as well:

    function DynamicLoader(props) {
      return (
        <Suspense fallback={<div>Loading...</div>}>
          React.lazy(() => import(`${props.ponent}`))
        </Suspense>
      );
    }
    
  2. In this line

    return <Route exact path={prop.path} ponent={c} key={key} />;  
    

    As the name of the prop ponent suggests, you need to pass a ponent and not an element you can read more about the difference in the DOCS.

    So you'll need to change it to this:

    return <Route exact path={prop.path} ponent={() => c} key={key} />;
    
  3. You are right. I missed the children part, you are rendering a string. You can create a variable and just render it as the child:

    function DynamicLoader(props) {
      const LazyComponent = React.lazy(() => import(`${props.ponent}`));
      return (
        <Suspense fallback={<div>Loading...</div>}>
          <LazyComponent/>
        </Suspense>
      );
    }
    
发布评论

评论列表(0)

  1. 暂无评论