zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    初识spring
    关于导入别人的web项目,tomcat无法显示的问题
    doPost无法跳转显示信息,只能下载文件查看
    socket网络编程
    log日志文件
    第三方模块安装
    __name__ __doc__ __package__
    格式化
    导入模块
    python正则表达式补充
  • 原文地址:https://www.cnblogs.com/wanghao123/p/11156194.html
Copyright © 2011-2022 走看看