实现对各模块状态操作等管理
具体文件功能如下:
action文件夹: 派发行文对象的分模块管理
reducers :reducer模块化管理
action-types.js : 派发行为标识的统一管理
combineReducers
合并各个模块的reducer,最后创建出一个总的reducer
reducer:是最后合并的总的reducer
派发行为标识 actionTypes
统一管理需要派发的行为标识:
-
- 为了保证不冲突,我们一般都是这样命名:模块名_派发的行为标识「大写」
-
- 变量和存储的值是一致的
-
- 所有需要派发的行为标识,都在这里定义
工程化处理
1.把redux/状态按照模块进行划分和管理,把所有模块的reducer合并为一个即可!
reducers文件内操作 2.每一次任务派发,都会把所有模块的reducer,依次去执行,派发时候传递的行为对象(行为标识)是统一的!!所以我们要保证:各个模块之间,派发的行为标识它的唯一性!!===>派发行为标识的统一管理!!
3.创建actionCreator对象,按模块管理需要派发的行为对象! action文件创建
工程化后的代码使用
具体实现的Demo文件与Redux了解、安装及简单使用 内的文件一致,我直接展示工程化后需要注意的位置:
1.获取数据变化
下面的结果是store运行后,产生的变量值,
获取内部变量值: store.getState().xxxx xxxx为模块名称
2.派发操作:
store.dispatch(action.count.sub())
具体实现的Demo文件与Redux了解、安装及简单使用 内的文件一致,有兴趣的小伙伴可以对比下,我这里直接展示工程化后需要注意的位置:
可以和下方代码对照着看!!!
store全量代码
**引入操作使用等操作与 Redux了解、安装及简单使用**内一致
store目录结构
store/index.js
import { legacy_createStore as createStore } from 'redux';
import reducer from './reducers';
const store = createStore(reducer);
export default store;
store/action-types.js
export const COUNT_INCREASE = "COUNT_INCREASE";
export const COUNT_DECREASE = "COUNT_DECREASE";
reducers
// index.js
import { combineReducers } from "redux";
import countReducer from './countReducer';
const reducer = combineReducers({
count: countReducer
});
export default reducer;
// countReducer.js
import * as TYPES from '../action-types'
let initial = {
count: 0
};
export default function countReucer(state = initial, action) {
state = { ...state };
switch (action.type) {
case TYPES.COUNT_INCREASE:
state.count++;
break;
case TYPES.COUNT_DECREASE:
state.count--;
break;
default:
}
// return的内容,会整体替换STORE容器中的状态信息
return state;
};
action
// index.js
import countAction from './countAction'
const action = {
count: countAction
}
export default action
// countAction.js
import * as TYPES from '../action-types'
const countAction = {
add() {
return {
type: TYPES.COUNT_INCREASE
}
},
sub() {
return {
type: TYPES.COUNT_DECREASE
}
}
}
export default countAction