一、作用
在一个项目中,组件可以有许多个,而每个组件都应该自己的store和reducer。如果把整个项目所有组件的store和reducer都放在一个文件中,文件会显得臃肿,不利于维护。
二、reducer的拆分
假如原本项目的结构是:
- store
- index.js
- reducer.js
- Component
- Header
- Article
组件Header,Article的state都存在根目录的store中,那么store会显得臃肿,而且Header,Article也显得不那么模块化。
现在将store拆分到各个组件中,目录结构是:
- store
- index.js
- reducer.js
- Component
- Header
- store
- index.js
- reducer.js
- Article
- store
- index.js
- reducer.js
在整合时,需要用到redux-immutable,要先安装:
npm install redux-immutable
在组件各自的reducer.js中创建各自的reducer,比如:
const defaultState = {
// ...
};
export default (state = defaultState, action) => {
// ...
}
然后,在组件中store的index.js导出各自的reducer
import reducer from './reducer';
export { reducer };
最后在根目录中的store/reducer.js整合reducer
import { combineReducers } from 'redux-immutable'
import { reducer as headerReducer } from './Component/Header/store';
import { reducer as articleReducer } from './Component/Article/store';
// 整合reducer
const reducer = combineReducers({
header: headerReducer,
article: articleReducer
});
export default reducer;
至此,reducer拆分完成。
三、拆分后的使用
- 获取state
// 比如在Header组件
// ... 使用了react-redux和immutable
const mapStateToProps = (state) => ({
todoList: state.get(['header', 'todoList']), // 在header下获取todoList
})
- 改变state(在reducer.js)
// ...
export default (state = defaultState, action) => {
switch(action.type){
case 'add_item': {
const todoList = state.get('todoList').toJS();
todoList.push(action.value);
return state.set('todoList', fromJS(todoList));
};
// ...
}
}
网友评论