reducer拆分
- 在对应的组件的文件下创建store文件
- 把主store的reducer.js 做变动
import { combineReducers } from'redux';
import headerReducer from '../common/header/store/reducer';
const reducer = combineReducers({
header:headerReducer
});
export default reducer;
const mapStateToProps = (state) => {
return {
focuse:state.header.focuse,
list:state.header.list
}
};
组件 store做一个公共的出口文件 index.js
//组件下的store文件下的index.js
import reducer from './reducer';
import * as actionCreators from './actionCreators';
import * as actionTypes from './actionTypes'
export { reducer , actionCreators , actionTypes} ;
//项目主store文件下的reducer.js
import { combineReducers } from'redux';
import { reducer as headerReducer } from '../common/header/store';//as 取别名
const reducer = combineReducers({
header:headerReducer
});
export default reducer;
//组件文件中做修改
import { actionCreators } from './store'
const mapStateToProps = (state) => {
return {
focuse:state.header.focuse,
list:state.header.list
}
};
const mapDispatchToProps = (dispatch) => {
return {
changeFocuse () {
store.dispatch(actionCreators.changeFocuse())
},
changeBlue () {
store.dispatch(actionCreators.changeBlur())
}
}
}
reducer不能直接修改store中的state,解决办法引入imutable.js
- 安装immutable yarn add immutable
- 使用
//reducer.js
import { fromJS } from 'immutable';
//转化state对象为immutabel对象
const defaultState = fromJS({
focuse:false,
list:[]
});
//组件中的使用就需要改变,因为state.header变成了immutable对象,就不能直接使用.的方式获取,要用get(属性)来获取
const mapStateToProps = (state) => {
return {
//老的
//focuse:state.header.focuse,
//list:state.header.list,
focuse:state.header.get('focuse'),
list:state.header.get('list')
}
};
//要改变state的数据也应该为immutable对象
//例如
import {fromJS} from 'immutable';
export const initList = (list) => ({
type:actionTypes.INIT_LIST,
list:fromJS(list)
})
- reducer.js中设置state值的时候就不用深拷贝了,直接使用set('属性',值),值必须是immutable对象
export default ( state = defaultState , action ) => {
switch (action.type){
case actionTypes.CHANGE_FOCUSE:
return state.set("focuse",true);
case actionTypes.CHANGE_BLUR:
return state.set("focuse",false);
case actionTypes.INIT_LIST:
return state.set("list",action.list);
default:
return state
}
}
- 上面虽然使用了immutable,但是只是header下的数据才是immutable对象,为了让所有的数据都是immutable对象,则需引入redux-immutable
//安装 yarn add redux-immutable
//使用
//项目主store中reducer.js修改
import { combineReducers } from'redux-immutable';
//组件中修改
const mapStateToProps = (state) => {
return {
list:state.getIn(['header','list']),
focuse:state.getIn(['header','focuse']),
// focuse:state.header.get('focuse'),
// list:state.header.get('list')
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。