Skip to main content

支持多个reducer

主要 API

  • createStore
  • getState
  • dispatch
  • subscribe
  • combineReducers // 新增

Core

const combineReducers = (reducers) => {
return (state, action) => {
const combineState = {}
const keys = Object.keys(reducers)
for (let key of keys) {
const partial = reducers[key](state === undefined ? state : state[key], action)
combineState[key] = partial
}
return combineState
}
}

const createStore = (reducer) => {
let state = reducer(undefined, {})
const listener = []

return {
getState: () => {
return state
},
subscribe: (fn) => {
listener.push(fn)
},
dispatch: (action) => {
state = reducer(state, action)
for (let fn of listener) {
fn && fn()
}
}
}
}

测试代码

const initCounterState = {
value: 0,
name: 'counter reducer'
}

const initTodoState = {
value: 0,
name: 'todo reducer'
}

const counterReducer = (state = initCounterState, action) => {
switch (action.type) {
case 'COUNTER/INCREMENT':
return {
...state,
value: state.value + (action.payload || 1)
}
case 'COUNTER/DECREMENT':
return {
...state,
value: state.value - (action.payload || 1)
}
default:
return {
...state
}
}
}

const todoReducer = (state = initTodoState, action) => {
switch (action.type) {
case 'TODO/INCREMENT':
return {
...state,
value: state.value + (action.payload || 1)
}
case 'TODO/DECREMENT':
return {
...state,
value: state.value - (action.payload || 1)
}
default:
return {
...state
}
}
}

const reducer = combineReducers({
counterReducer,
todoReducer,
})
const store = createStore(reducer)

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

console.log('add todo 10')
store.dispatch({
type: 'TODO/INCREMENT',
payload: 10
})

console.log('add counter 5')
store.dispatch({
type: 'COUNTER/INCREMENT',
payload: 5
})

console.log('minus todo 2')
store.dispatch({
type: 'TODO/DECREMENT',
payload: 2
})