react之路:使用combineReducers拆分reducer


github倉庫地址:https://github.com/wanghao12345/react-book

背景

如果一個項目,比較大,需要redux存儲的狀態數據比較多時,reducer.js無疑是會非常臃腫的。所以為了簡化reducer.js文件,我們應該按照功能模塊將這個大的reducer.js文件,拆分成若干個reducer.js。那么這里就需要使用redux里面的一個方法:combineReducers

步驟

1.在各個需要使用redux的功能模塊下建立自己的reducer.js文件,大體格式如下:

 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引入combineReducers

 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為例

1 /**
2  * 將倉庫的state映射到props(獲取state)
3  * @param state
4  */
5 const mapStateToProps = (state) => {
6     return {
7         focused: state.header.focused
8     }
9 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM