如何使用react-loadable与react-router? [英] How can I use react-loadable with react-router?
问题描述
我正在尝试实现一个包含10-15页的应用程序。这适用于react-router,但我应该使用react-loadable来获得Spinner和加载效果...
I am trying to implement an application that has 10-15 pages. That works with react-router well but I should use react-loadable to have a Spinner and loading effect ...
但是如何在可加载的内部导入路由器组件?
But how can I import router components inside the loadable ?
我应该为每个组件创建一个const变量吗?
I should create one const variable for each component ?
像这样:
const Home = Loadable({
loader: () => import('./Home'),
loading: Loading,
});
const News = Loadable({
loader: () => import('./News'),
loading: Loading,
});
const Gallery = Loadable({
loader: () => import('./Gallery'),
loading: Loading,
});
class App extends React.Component {
render() {
return (
<Router>
<Route exact path="/" component={Home} />
<Route path="/news" component={News} />
<Route path="/gallery" component={Gallery} />
</Router>
)
}
}
还是可以使用其他技巧?
Or it's possible with other tricks ?
推荐答案
这有点棘手。你不需要使用反应加载。
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 :(
你可以创建一个名为<$ c $的新文件c> 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>
这篇关于如何使用react-loadable与react-router?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!