【问题标题】:Make React component load before displaying it在显示之前加载 React 组件
【发布时间】:2020-01-19 02:21:45
【问题描述】:

我正在使用 React 钩子,我希望我的组件在显示之前实际完成整个加载。

我目前的解决方案是这样的:

import React, {useState, useEffect} from 'react'
import Main from './Main'

export default function Container() {

     const [isLoading, setisLoading] = useState(false);

     useEffect(() => {
        setTimeout(() => setisLoading(true), 1000)
     })

return (
        <div>
           {(isLoading) ? <Main/> : <h1>I'm currently loading</h1>}
        </div>
      );
}

这里的问题是它加载了 1 秒,然后显示了我的 Main.js 组件,这需要大约 2 秒才能加载。我希望在显示组件之前完成实际加载。

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

你可以试试react lazy loading

const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <OtherComponent />
      </Suspense>
    </div>
  );
}

【讨论】:

    【解决方案2】:

    你所拥有的一切都很好,你只是让加载状态倒退。加载默认为true,1000ms后设置为false。

    当 loading 为真时,显示你的加载信息,然后显示你的组件。

    import React, { useState, useEffect } from "react";
    import ReactDOM from "react-dom";
    
    function Main() {
      return <h1>I'm a main component</h1>;
    }
    
    export default function Container() {
      const [isLoading, setisLoading] = useState(true);
    
      useEffect(() => {
        setTimeout(() => setisLoading(false), 1000);
      });
    
      return <div>{isLoading ? <h1>I'm currently loading</h1> : <Main />}</div>;
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<Container />, rootElement);
    

    【讨论】:

      【解决方案3】:

      您应该设置正确的导入和代码拆分变体。

      你可以在这里找到它的好指南和图书馆:https://github.com/jamiebuilds/react-loadable

      如果你想自己创建,你可以这样写代码:

      export default function Container() {
      
           const [Main, setMain] = useState(null);
      
           useEffect(() => {
                 import('/path/to/main').then(main => setMain(main));
           }, [])
      
      return (
              <div>
                 {(isLoading) ? <Main/> : <h1>I'm currently loading</h1>}
              </div>
            );
      }
      

      此变体适用于客户端和服务器端。

      你也可以使用 React.lazy,但它不适用于服务器端渲染

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-19
        • 1970-01-01
        • 2012-02-27
        • 1970-01-01
        • 2015-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多