leseul-yj / Benchmarking

react-router antd
1 stars 0 forks source link

redux #1

Open leseul-yj opened 4 years ago

leseul-yj commented 4 years ago

redux原理

leseul-yj commented 4 years ago

let countDisplay = document.getElementById("countDisplay") let countState = { count: 100 }

const changeState = (state,action) => { if(!state) { return countState; } switch(action.type) { case "JIAN": return { ...state, count: state.count - action.n }; case "JIA": return { ...state, count: state.count + action.n }; default: return state } }

const createStore = (changeState) => { let state = null; const getState = () => state; const listeners = [];//监听数组 const subscribe = (listener) => listeners.push(listener); const dispatch = (action) => { state = changeState(state,action); listeners.forEach(listener => listener()) } dispatch({}) return { getState, dispatch, subscribe } } // changerState 相当于一个reducer const store = createStore(changeState);

const renderCount = () => { countDisplay.innerHTML = store.getState().count; } renderCount()

store.subscribe(renderCount)