转载

如何让redux actions reducers 按需加载!

背景

最近项目中用了react-router。把业务拆分了很多模块,比如ABCD...模块,react-router 可以在需要的适合做到按需加载这些业务代码。

数据流采用redux,actions和reducers有统一的处理,也有各业务模块的的actions和reducers。你会发现,actions和reducers需要在一开始就定义好。也就是说A业务的actions/reducers做不到按需加载啦,即使用户可能压根就没有访问到A业务。假设你的actions和reducers很复杂,那就白白浪费了很多带宽。

网上找了下,貌似没有相关的信息和现成的解决方案。所以才有了 redux-async-actions-reducers

redux-async-actions-reducers

(有疑问先issue沟通)redux 可以通过combineReducers把reducer拆分, actions也可以放在不同的文件上定义。

但按需加载貌似不行。 于是造了个

demo

git clone https://github.com/liyatang/redux-async-actions-reducers.git git checkout gh-pages npm install npm start

用法

按需加载actions

以前

import {bindActionCreators} from'redux';  // ...省略  App = connect(state => state, dispatch => ({     actions: bindActionCreators(actions, dispatch) }))(App);

now

import {bindAsyncActions} from 'redux-async-actions-reducers';  // ...省略  App = connect(state => state, dispatch => ({     actions: bindAsyncActions(actions, dispatch) }))(App);

把 bindActionCreators 切换成 bindAsyncActions。 这样 actions 被 redux-async-actions-reducers 接管,就可以通过 mapActions 来按需加载 actions 了。

// 某A业务的 actions 按需加载进来 import {mapActions} from 'redux-async-actions-reducers';  // map 进来 mapActions({     something(){} });

按需加载 reducers

以前

import {combineReducers} from 'redux';  // ...省略  const rootReducers = combineReducers(reducers);

now

import {combineAsyncReducers} from 'redux-async-actions-reducers';  // ...省略  // reducers 的初始状态需要在这里定义。 combineAsyncReducers 接管 reducers 后会转换成function. // 每个reducers的state初始状态请在这里定义. 因为一开始redux会跑一个@INIT的action,把所有state初始化一遍。 let reducers = {     a: {},     b: {} }  const rootReducers = combineAsyncReducers(reducers);

把 combineReducers 切换 combineAsyncReducers。 这样 reducers 被 redux-async-actions-reducers 接管,就可以通过 mapReducers 来按需加载 reducers 了。

// 某A业务的reducers按需加载进来 import {mapReducers} from 'redux-async-actions-reducers';  mapReducers({     something(state, action){         switch (action.type) {           // ... 省略         }     } });
正文到此结束
Loading...