簡體   English   中英

React.lazy & Suspence,延遲加載組件

[英]React.lazy & Suspence,Lazy loading component

我試圖創建 LLC https://blog.logrocket.com/lazy-loading-components-in-react-16-6-6cea535c0b52/但最終我得到了錯誤:

Objects are not valid as a React child (found: object with keys {$$typeof, _ctor, _status, _result}). If you meant to render a collection of children, use an array instead.
<LazyLoadingComponent resolve={() => import('../StaticComponents/Notification/Notification')}>
</LazyLoadingComponent>
import React, { lazy, Suspense } from 'react';

function LazyLoadingComponent({ resolve }) {
  console.log('resolve', resolve);
  return (
    <Suspense fallback={() => <h1>loading</h1>}>
      {lazy(async () => {
        const { default: module } = await resolve();
        console.log(module, 'module');
        return module;
      })}
    </Suspense>
  );
}

export default LazyLoadingComponent;

嘗試這個:

// App.js
import React, { lazy, Suspense } from "react";
// Import your compnent like so
const LazyComponent = lazy(() => import("./LazyComponent"))

function App() {
  return (
    <div className="App">
      <h1>Testing Lazy component..</h1>
      <Suspense fallback={<h2>See Loading?</h2>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
}

你的懶惰組件:

// LazyComponent.js
import React from "react";

export default function LazyComponent() {
  return (
    <div>
      <h1>I'm Lazy</h1>
      <p>
        This is my lazy component!
      </p>
    </div>
  );
}

代碼沙盒示例。

無論如何,這有效,感謝您的幫助!

<LazyLoadingComponent
  component={lazy(() => import('../StaticComponents/Notification/Notification'))}
 ></LazyLoadingComponent>
    <Suspense fallback={() => <h1>loading</h1>}>
      <Component></Component>
    </Suspense>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM