// 简化版createStore函数 const createStore = (yourReducer) => { let listeners = []; let currentState = yourReducer(undefined, {}); return { getState: () => currentState, dispatch: (action) => { currentState = yourReducer(currentState, action); listeners.forEach((listener) => { listener(); }); }, subscribe: (newListener) => { listeners.push(newListener); const unsubscribe = () => { listeners = listeners.filter((l) => l !== newListener); }; return unsubscribe; } }; }; // Redux的架构组成部分 const initialState = { count: 0 }; const actions = { increment: { type: 'INCREMENT' }, decrement: { type: 'DECREMENT' } }; const countReducer = (state = initialState, action) => { switch (action.type) { case actions.increment.type: return { count: state.count + 1 }; case actions.decrement.type: return { count: state.count - 1 }; default: return state; } }; const store = createStore(countReducer); // DOM元素 const incrementButton = document.querySelector('.increment'); const decrementButton = document.querySelector('.decrement'); // 给按钮添加点击事件 incrementButton.addEventListener('click', () => { store.dispatch(actions.increment); }); decrementButton.addEventListener('click', () => { store.dispatch(actions.decrement); }); // 初始化UI视图 const counterDisplay = document.querySelector('h1'); counterDisplay.innerHTML = parseInt(initialState.count); // 派发动作的时候跟新UI store.subscribe(() => { const state = store.getState(); counterDisplay.innerHTML = parseInt(state.count); });
我们再次看看最后的视图效果:
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。
原文: https://www.freecodecamp.org/news/redux-in-24-lines-of-code/