zoukankan      html  css  js  c++  java
  • 手动实现redux(二)

    一个app中store(状态树)是唯一的

    我们知道对于一个app, store应该是唯一,集中用reducer管理的,那么当app中有多个页面,每个页面有多个组件时,就应该有多个reducer来管理。
    当我某个组件dispatch出去一个action(动作)时,store接收到action,应该交给谁来管理呢?这里我们暂时无法使store根据不同的action来交由相应的reducer处理。
    

    combineReducer

    combineReducer函数将多个不同的reducer整合在一起,然后返回一个整合后的reducer, 也就是一个函数;函数内部通过分治的方式处理不同的action;
    

    代码实现

    注意combineReducer函数仍然属于reduxde一部分, 所以我们只需要在上一节的代码中添加即可。

    let combineReducer = (reducersObj){
                        //        reducerObj是一个由所有所需reducer组成的对象
            return (state={}, action={ type: Symbol() })=>{
                        //        返回值其实就是一个rootReducer, 所以参数是state, action 
                        //         注意这个rootReducer其实就是在创建store的时候传入的reducer. 
                        //        上一节中,创建store的时候需要先调用一下reducer(), 以得到state的默认状态值;此时相当于调用rootReducer({}, {type; Symbol()}) 
                        //        所以这里给action设置了一个默认值, 注意这里使用了Symbol这样会是action.type无法匹配到用户定义任何的actionTypes 
                        //        rootReducer会返回一个新的state 
            let newState = {};
                        //        当我们接收到一个action时,我们无法知道该交由哪个reducer处理, 所以这里我们 需要遍历所有reducer 
            for (let key in reducersObj){
              newState[key]  =  reducersObj[key](state[key], action)
                        //        这样一个reducer就成为了store状态树中的子树 
                        //         比如页面中有todo, counter两个组件对应着两个reducer, reducersObj = {todo, counter} 
                        //        store状态树大概长这样: {todo: {list: [], counter: {number : 0}} 
            }
            return newState;
        }
    }
    

    最后将 combineReducer导出即可

    combineReducer使用

    一般来说,在一个app项目目录中,我们都会将reducer独立出来,建立一个reducers文件夹,里面就是各个app中所需的reducer, 然后这个文件夹里还有一个index.js文件

    1. 在这个index.js中我们通常会先引入所有的reducer,并且引入combineReducer

       import counter from './counter';
       ...
       import todo from './todo';
       import { combineReducers } from "./../redux";
      
       const rootReducer = combineReducers({
           counter,
           todo,
           ....
       });
       export default rootReducer;
      
    2. 在store.js文件中引入rootReducer

       import { createStore } from "redux";
       import rootReducers from "./reducers/index";
       export default const store = createStore(rootReducers);
      
  • 相关阅读:
    centos7.7环境下编译安装tengine2.3.2版本
    centos6.9安装python3.6.9独立的virtualenv环境,并且能正确引入ssl
    django在centos生产环境的部署
    django入门8之xadmin引入富文本和excel插件
    jenkins服务器使用python脚本rabbitmqadmin和shell对目标服务器进行管理
    django入门7之django template和xadmin常用技巧
    mysql5.7同步复制报错1060故障处理
    Centos7.6使用yum安装PHP7.2
    django中安全sql注入等
    django入门6引入验证码插件 django-simple-captcha
  • 原文地址:https://www.cnblogs.com/paopaolee/p/9505114.html
Copyright © 2011-2022 走看看