Redux入门0x103: 拆分多个 reducer

0x001 概述

这一章讲多个reducer怎样处置惩罚,并将ledux搞成支撑支撑多个reducer

0x002 拆封reducer

import {createStore, combineReducers} from 'redux'

const ACTION_NUM1_INCREMENT = 'ACTION_NUM1_INCREMENT'
const ACTION_NUM2_INCREMENT = 'ACTION_NUM2_INCREMENT'

const num1 = (state = 0, action) => {
    switch (action.type) {
        case ACTION_NUM1_INCREMENT: {
            return ++state
        }
        default: {
            return state
        }
    }
}

const num2 = (state = 0, action) => {
    switch ((action.type)) {
        case ACTION_NUM2_INCREMENT: {
            return ++state
        }
        default: {
            return state
        }
    }
}

const reducer = combineReducers({
    num1: num1,
    num2: num2
})
let store = createStore(reducer)

store.subscribe(() => {
    console.log(store.getState())
})

store.dispatch({type: ACTION_NUM1_INCREMENT})
store.dispatch({type: ACTION_NUM2_INCREMENT})

检察浏览器
《Redux入门0x103: 拆分多个 reducer》

就是这么简朴了,中心函数是:combineReducers(reducers),将多个reducer并成一个,拆分以后呢,每一个reducer零丁治理一个state

0x002 革新ledux使之支撑combineReducers

  • 增加combineReducers并修正state盘算逻辑
class Ledux {
    static createStore(reduer) {
        return new Store(reduer)
    }

    static combineReducers(reducers) {
        return reducers
    }
}

class Store {
    constructor(reducer) {
        this.state = this.calculateState(reducer)
        this.callbacks = []
        this.reducer = reducer
    }

    subscribe(callback) {
        this.callbacks.push(callback)
    }

    getState() {
        return this.state
    }

    dispatch(action) {
        this.state = this.calculateState(this.reducer, action)
        this.callbacks.forEach(callback => callback())
    }

    /**
     * reducer 多是一个经由 combineReducers 的对象
     * 所以须要推断 reducer 是不是是一个对象
     * 假如是
     *  那申明这是一个复合的 reducer
     *  须要轮回盘算出每一个 state
     *  并以对象的情势保存到 state
     * 假如不是对象并且是函数
     *  那申明这是一个单一的 reducer
     *  直接盘算就好了
     *  然后保存到 state
     *
     * @param reducer 单一的 reducer 函数或许 combineReducers 以后的对象
     * @param action
     * @returns {*}
     */
    calculateState(reducer, action = {}) {
        if (typeof reducer === 'object') {
            return Object.keys(reducer).map((key) => {
                return {
                    [key]: reducer[key](undefined, action)
                }
            }).reduce((pre, current) => {
                return {...pre, ...current}
            })
        } else if (typeof reducer === 'function') {
            return reducer(undefined, action)
        }
    }
}
/**
 * 增加几个函数导出
 * 坚持和 redux 一致的 api
 * 如许就能够不修正挪用的函数了
 */
const createStore = Ledux.createStore
const combineReducers = Ledux.combineReducers
export {createStore, combineReducers}
export default Ledux
  • 修正挪用
// 直接修正 redux 引入就好了
import {createStore, combineReducers} from './ledux'

0x003 总结

0x004 资本

    原文作者:followWinter
    原文地址: https://segmentfault.com/a/1190000016270335
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞