在使用了 redux 的项目,普遍存在同样的问题:随着项目规模的增长, reducer 数量和代码量也相应增加。本身 redux 并未提供完善的 reducer 代码分块方案。lazy-reducer
通过提供 Container (容器组件) 和 HOC (高级组件) 两种方式简化 reducer 的代码分块问题。
npm install --save-dev lazy-reducer
使用 lazy-reducer
你唯一需要做的:添加一个 store enhencer 。
** 注 **:lazyReducerEnhancer 接受的参数是一个reducers的对象,不是 combineReducers(reducers) 后的 reducer 方法。
import { lazyReducerEnhancer } from 'lazy-reducer';
const rootReducerObj = {
nameA: reducerA,
nameB: reducerB
};
const store = createStore(combineReducers(rootReducerObj), {}, lazyReducerEnhancer(rootReducerObj));
内联在 LazyReducer
中的子组件,只有当 reducers
被注册到 redux 中才会被渲染。
import { LazyReducer } from 'lazy-reducer';
<LazyReducer
reducers={done => {
import('./someReducer').then((reducer) => {
done({
nameA: someReducer
})
})
}}
>
<AnyComponent />
</LazyReducer>
被 withLazyReducer
高阶组件嵌套的组件,只有当 reducers
被注册到 redux 中才会被渲染。
import { withLazyReducer } from 'lazy-reducer'
class Comp extends Component {
render() {
<div>i am a Component wrapped by lazy reducer !</div>
}
}
export default withLazyReducer(done => {
import('./someReducer').then((reducer) => {
done({
nameA: someReducer
})
})
})(Comp)
@withLazyReducer(done => {
import('./someReducer').then((reducer) => {
done({
nameA: someReducer
})
})
})
class Comp extends Component {
render() {
<div>i am a Component wrapped by lazy reducer !</div>
}
}
import { LazyReducer } from 'lazy-reducer'
import Homepage from './Homepage'
const route = {
path: '/homepage',
component: (
<LazyReducer
reducers={done => {
import('./homepageReducer').then(reducer => {
done({
homepage: reducer.default
})
})
}}
>
<Homepage />
</LazyReducer>
)
}