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 }
  • 相关阅读:
    关于Linux 上建立生成/添加SSH公钥
    sql随机插入数据--记录
    centos 安装搜狗
    centos yum命令找不到包
    命令行改为图形界面
    CentOS7l联网
    .net mvc 框架实现后台管理系统 3
    .net mvc 框架实现后台管理系统 2
    .net mvc 框架实现后台管理系统
    爬取猫眼数据
  • 原文地址:https://www.cnblogs.com/wanghao123/p/11156194.html
Copyright © 2011-2022 走看看