zoukankan      html  css  js  c++  java
  • [React] Preload React Components with the useEffect Hook

    Let's say we are using 'React.lazy()' to lazy load some Router:

    const Home = React.lazy(() => import('./screens/home'))
    const User = React.lazy(() => import('./screens/user'))
    
    function ErrorFallback({error}) {
      return (
        <IsolatedContainer>
          <p>There was an error</p>
          <pre style={{maxWidth: 700}}>{JSON.stringify(error, null, 2)}</pre>
        </IsolatedContainer>
      )
    }
    
    function App() {
      return (
        <ThemeProvider>
          <GitHubContext.Provider>
            <ErrorBoundary FallbackComponent={ErrorFallback}>
              <Suspense
                fallback={
                  <LoadingMessagePage>Loading Application</LoadingMessagePage>
                }
              >
                <Router>
                  <Home path="/" />
                  <User path="/:username" />
                </Router>
              </Suspense>
            </ErrorBoundary>
          </GitHubContext.Provider>
        </ThemeProvider>
      )
    }
    
    const ui = <App />
    const container = document.getElementById('root')
    
    ReactDOM.render(ui, container)

    One problem for lazy loading router is that for slow connect user, it takes take to switch page. What we can do to solve the problem is by preload the lazy loaded router.

    Let's say once user arrived on 'Home' Page, we assume he will continue to 'User' page. So we will preload 'User' page inside Home page.

    function Home() {
      useEffect(() => {
        // preload the next page
        import('../user')
      }, [])
      return (
        <IsolatedContainer>
          <form
            onSubmit={handleSubmit}
            css={{
              display: 'flex',
              justifyContent: 'center',
              maxWidth: 240,
              margin: 'auto',
            }}
          >
            <Input
              type="text"
              name="username"
              placeholder="Enter a GitHub username"
              autoFocus
              css={{
                borderRight: 'none',
                borderTopRightRadius: '0',
                borderBottomRightRadius: '0',
                minWidth: 190,
              }}
            />
            <PrimaryButton
              css={{
                borderTopLeftRadius: 0,
                borderBottomLeftRadius: 0,
              }}
              type="submit"
            >
              Go
            </PrimaryButton>
          </form>
        </IsolatedContainer>
      )
    }
  • 相关阅读:
    逻辑思维杂想
    C++二叉树实现
    斐波那数列递归实现与动态规划实现
    C++双向链表的实现
    C++单链表实现
    C++顺序表实现
    windows下端口占用处理工具
    [项目记录]一个.net下使用HAP实现的吉大校园通知网爬虫工具:OAWebScraping
    [c++]大数运算---利用C++ string实现任意长度正小数、整数之间的加减法
    [C++]几种排序
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12806118.html
Copyright © 2011-2022 走看看