根据源码结合自己的理解写出的简单代码。
不知道redux是否是这个原理。
export default function (counter, defaultState){
let state = defaultState || counter(undefined, {})
let subscribe = []
return {
dispatch(action){
let newState = counter(state, action)
if (state === newState) return
state = newState
subscribe.forEach(fun=>fun(state))
},
getState(){
return state
},
subscribe(fun){
subscribe.push(fun)
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…