[英]Code splitting with React Loadable and routes with containers
I want to achieve code splitting of every main route so every page will have its own file (along with its subcomponents), for example I have a main render function with Route
components that points to containers: 我想实现每个主路径的代码拆分,以便每个页面都有其自己的文件(及其子组件),例如,我有一个主渲染功能,其中
Route
组件指向容器:
<Route path={`path1`} component={foo.container} />
<Route path={`path2`} component={bar.container} />
Each container looks something like this: 每个容器看起来像这样:
const mapDispatchToProps = {
... actions etc ...
}
const mapStateToProps = (state) => ({
... selectors etc ...
})
const withConnect = connect(mapStateToProps, mapDispatchToProps);
export default compose(withConnect)(MyComponent);
I tried to wrap a container and reference that in the route but it didn't work: 我试图包装一个容器并在路线中引用它,但是它没有用:
export default Loadable({
loader: () => import('./MyContainer'),
loading() {
return (<div>Loading...</div>)
},
});
So what am supposed to wrap then? 那么,应该包装什么呢?
Here is a simplified example how to achieve code splitting with react-router
and react-loadable
: 这是一个简化的示例,说明如何使用
react-router
和react-loadable
实现代码拆分:
MyPage.jsx - the page what you want to generate in a separate file MyPage.jsx- 您要在单独文件中生成的页面
import React from 'react';
const MyPage = () => (
<div>My page</div>
);
export default MyPage;
LoadableMyPage.jsx - wrapper to make your page loadable LoadableMyPage.jsx- 使您的页面可 加载的 包装器
import React from 'react';
import Loadable from 'react-loadable';
const LoadableMyPage = Loadable({
loader: () => import('./MyPage'),
loading: () => <div>Loading...</div>,
});
const LoadableMyPage = () => (
<LoadableMyPage />
);
export default LoadableMyPage;
Router.jsx Router.jsx
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import LoadableMyPage from './LoadableMyPage';
const Router = () => (
<Switch>
<Route path="/" exact component={LoadableMyPage} />
...
</Switch>
);
As @Mohit Tilwani mentioned, the dynamic import plugin is required because it's currently in stage-3
and not part yet of the ECMAScript. 正如@Mohit Tilwani所述,动态导入插件是必需的,因为它目前处于
stage-3
而不是ECMAScript的一部分。
https://github.com/tc39/proposal-dynamic-import
https://github.com/tc39/proposal-dynamic-import
I started working on my own React boilerplate where I implemented the same code splitting. 我开始在自己的React样板中工作,在其中实现了相同的代码拆分。 Do not hesitate to check it if you got stucked.
如果被卡住,请立即检查。
https://github.com/peetya/react-boilerplate
https://github.com/peetya/react-boilerplate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.