且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用react-loadable与react-router?

更新时间:2023-12-01 19:53:46

这有点棘手。你不需要使用反应加载。

This is a bit tricky. You don't need to use react-loadable.

演示这里

如果你想为图像和其他组件加载,直到它们 onLoad ,您可以使用 react-content-loader 代替创建骨架屏幕(参见 components / Image.js 在演示中)。它可以使几乎完美的装载机。到目前为止,这是我能做的。我不知道为css检测 onLoad :(

If you want to make loader for images and other components until they are onLoad, you can use react-content-loader instead to create skeleton screens (See components/Image.js in demo). It could make "almost" perfect loader. So far, this is what I can do. I have no idea to detect onLoad for css :(

你可以创建一个名为 routes.js 包括所有页面。

You can create a new file named routes.js which includes all pages.

- /src
-- /pages
--- Gallery.js
--- Home.js
--- News.js
--- withBase.js
-- App.js
-- routes.js

routes.js

import Home from './pages/Home';
import Gallery from './pages/Gallery';
import News from './pages/News';
// Add as much as you want...

export default [
   {
       path: '/',
       component: Home,
   },
   {
       path: '/gallery',
       component: Gallery,
   },
   {
       path: '/news',
       component: News,
   },
];

您需要创建一个包含每个页面的高阶组件。

You need to create a high order component that will wrap each page.

withBase.js( HOC)强>

import React from "react";

export default WrappedComponent =>
  class extends React.Component {
    state = {
      isLoading: true
    };

    componentDidMount() {
      this.hideLoader();
    }

    hideLoader = () => {
      // This is for demo purpose
      const proc = new Promise(resolve => {
        setTimeout(() => resolve(), 3000);
      });
      proc.then(() => this.setState({ isLoading: false }));
    };

    render() {
      return (
        <div>
          {this.state.isLoading ? <p>Loading...</p> : <WrappedComponent />}
        </div>
      );
    }
  };

用法:例如 export default withBase(Home)

然后,在 App.js 只需循环路线。

Then, in App.js just loop the routes.

    <Switch>
      {routes.map(route => (
        <Route
          exact
          key={route.path}
          path={route.path}
          component={route.component}
        />
      ))}
    </Switch>