functioncreateStore (stateChanger) { let state = null const listeners = [] constsubscribe = (listener) => listeners.push(listener) constgetState = () => state constdispatch = (action) => { state = stateChanger(state, action) listeners.forEach((listener) =>listener()) } dispatch({}) // 初始化 state return { getState, dispatch, subscribe } }
createStore 内部的 state 不再通过参数传入,而是一个局部变量 let state = null。createStore 的最后会手动调用一次 dispatch({}),dispatch 内部会调用 stateChanger,这时候的 state 是 null,所以这次的 dispatch 其实就是初始化数据了。createStore 内部第一次的 dispatch 导致 state 初始化完成,后续外部的 dispatch 就是修改数据的行为了。
stateChange可以换一个名字,就叫他reducer,不要问,问就是reducer
1 2 3 4 5 6 7 8 9 10 11 12
functioncreateStore (reducer) { let state = null const listeners = [] constsubscribe = (listener) => listeners.push(listener) constgetState = () => state constdispatch = (action) => { state = reducer(state, action) listeners.forEach((listener) =>listener()) } dispatch({}) // 初始化 state return { getState, dispatch, subscribe } }