github倉庫地址:https://github.com/wanghao12345/react-bookhtml
若是一個項目,比較大,須要redux存儲的狀態數據比較多時,reducer.js無疑是會很是臃腫的。因此爲了簡化reducer.js文件,咱們應該按照功能模塊將這個大的reducer.js文件,拆分紅若干個reducer.js。那麼這裏就須要使用redux裏面的一個方法:combineReducersreact
1.在各個須要使用redux的功能模塊下創建本身的reducer.js文件,大致格式以下:git
1 const defaultState = { 2 focused: false 3 } 4 5 export default (state = defaultState, action) => { 6 7 if (action.type === 'search_focus') { 8 return { 9 focused: true 10 } 11 } 12 13 if (action.type === 'search_blur') { 14 return { 15 focused: false 16 } 17 } 18 19 return state 20 }
2.在store下的reducer.js引入combineReducersgithub
1 import { combineReducers } from 'redux' 2 import { reducer as headerReducer } from 'xxxxxxxx' 3 ...... 4 5 6 const reducer = combineReducers({ 7 header: headerReducer, 8 ...... 9 }) 10 11 export default reducer
3.使用的時候,須要注意,以上一節爲例,將倉庫的state映射到props這裏的mapStateToProps裏面return的數據須要加上自定義命名reducer名字,這裏以header爲例redux
1 /** 2 * 將倉庫的state映射到props(獲取state) 3 * @param state 4 */ 5 const mapStateToProps = (state) => { 6 return { 7 focused: state.header.focused 8 } 9 }