<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>redux原理</title> </head> <body> <button onclick="store.dispatch({type:'JIAN',n:2})">-</button><span id="countDisplay">10</span><button onclick="store.dispatch({type:'JIA',n:3})">+</button> </body> <script> const countDisplay = document.querySelector('#countDisplay') //因为countState是全局的 const countState = {count :5}; const changeState =(state,action)=>{ console.log('执行了3') if(!state){ console.log('执行了4') return countState } switch(action.type){ case 'JIA': // state.count +=action.n return { ...state,count: state.count+ action.n } break; case 'JIAN': //state.count -=action.n return { ...state,count: state.count+action.n } break; default: break } } //创建 const createStore = (changeState)=>{ let state = null const getState = ()=>state const listeners = [] const subscribe =(method)=>{ listeners.push(method) } const dispatch = (action)=>{ //因为不是全局的了,渲染只会渲染store返回的state,所以需要将最新的改变的值赋值给store返回的state中才能实现渲染,然后重新调用changeState方法的时候又将store内部最新的state传递进去在此基础上继续修改 state=changeState(state,action) listeners.forEach(method=>method()) // renderCount() //用数组将要执行的方法保留起来,因为除了renderCount可能还有render其他的需求 } console.log('执行了1') dispatch({}) console.log(listeners.length) console.log('执行了2') return { getState ,dispatch, subscribe } } // const renderCount =(state)=>{ // countDisplay.innerHTML = state.count // } //renderCount(countState) // const jian =(n)=>{ // countState.count=countState.count-n // renderCount(countState) // } // const dispatch =(action )=>{ // changeState(action) // renderCount(countState) // } const store = createStore(changeState) const renderCount =()=>{ console.log(5) countDisplay.innerHTML = store.getState().count } //需要自己手动执行一次 renderCount() store.subscribe(renderCount) </script> </html>