function reducer(state=1,action){
console.log(action)
switch(action.type){
case "add":
return state+1
case "minus":
return state-1
case "asyncAdd":
return state +10
}
}
function createStore(reducer,enhancer){
if(enhancer){
return enhancer(createStore)(reducer)
}
let currentState=1
let listeners=[]
function getState(){
return currentState
}
function dispatch(action){
console.log('dispatch',action)
currentState=reducer(currentState,action)
listeners.map(cb=>cb())
return action
}
function subscribe(cb){
listeners.push(cb)
console.log(listeners)
}
return {
getState,
dispatch,
subscribe
}
}
function applyMiddleware(...middlewares){
return createStore=>(...args)=>{
console.log('args',args)
const store=createStore(...args)
let dispatch=store.dispatch
const midApi={
getState:store.getState,
dispatch
}
const middleChain=middlewares.map(mw=>mw(midApi))
dispatch=compose(...middleChain)(store.dispatch)
return{
...store,
dispatch
}
}
}
const thunk = ({dispatch, getState}) => dispatch => action=> {
if (typeof action == 'function') {
return action(dispatch, getState)
}
return dispatch(action)
}
function compose(...funcs){
return funcs.reduce((left,right)=>(...args)=>right(left(...args)))
}
export const store=createStore(reducer,applyMiddleware(thunk))
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。