getState
, dispatch
, subscribe
listeners
数组存储重渲染的回调,subscribe
返回一个取消订阅函数const createStore = (reducer) => {
let state = {}
let listeners = []
const getState = () => state
const dispatch = (action) => {
state = reducer(state, action)
listeners.forEach(listener => listener())
}
const subscribe = (listener) => {
listeners.push(listener)
return () => {
listerners = listeners.filter(item => item !== listerner)
}
}
return {getState, dispatch, subscribe}
}
分组的映射可以用 forEach 处理,也可以用reduce 处理: 根据旧状态,把每条分组 reducer 生成的 分组状态逐个累加到 新状态上
const combineReducers = (reducers) => {
return (state ={}, action) {
return Object.keys(reducers).reduce(
(nextState, key) => {
nextState[key] = reducers[key](state[key], action)
return nextState
},
{})
}
}