优化
拆分 reducer
当 Reducer 中需要接收的 action 过多,且各个组件都有自己的 action、reducer、constants 时,可以将 reducer.js 分散到各个组件模块中。在总的 reducer 中使用 combineReducers ,将各个子 reducer 连接起来。
关系图
common/header - /store
/actionCreator.js
/constants.js
/reducer.js
/index.js - /index.js
store
/index.js
/reducer.js
Immutable 将 state 属性私有
在 Redux 的开发中,要求 store 中的 state,只能由其自己进行修改,因此我们可以使用 Immutable 来对 state 进行封装。将其改为一个不可变对象。
只能通过操作 Immutable 提供的 get、set 方法来修改数据。
1. 引入依赖
yarn add immutable // 项目中添加 Immutable 依赖
2. 将 state 转换为 Immutable 对象
在使用时,将 state 通过 Immutable 提供的 fromJS 方法进行包装。包装之后的 state 便无法再通过 . 属性的方式获取到值。非常类似 Java 中的封装。
下面是 Header 组件的 reducer.js:
import { fromJS } from "immutable";
const defaultState = fromJS({
value: "Hello React !",
focused: false
});
export default (state = defaultState, action) => {
switch (action.type) {
case "aaa":
return state.set("value", action.value);
case "bbb":
return state.set("focused", true);
default:
return state;
}
};
3. 将子组件的 state 转换为 Immutable 对象
重点是将 combineReducers 方法,改为从 redux-immutalbe 中获取。
import { combineReducers } from "redux-immutable";
import { reducer as headerReducer } from "../common/header/store";
const reducers = combineReducers({
header: headerReducer
});
export default reducers;
4. Header 组件使用 state.header.value
下面是使用 redux-saga 进行组件与 store 的连接,请查阅 Redux-Saga
class Header extends Component {
// ......
}
const mapStateToProps = (state) => {
return {
value: state.get('header').get('value'),
focused: state.get('header').get('focused'),
list: state.get('header').get('list')
}
}
const mapDispatchToProps ...
export default connect(mapStateToProps,mapDispatchToProps)(Header);