HTML結構以下spa
<div> <p>Count: <span id="value">0</span></p> <button id="btn_increase">+ 1</button> <button id="btn_decrease">- 1</button> </div>
JavaScript結構以下code
function counter (state = 0, action) { switch (action.type) { case 'INCREASE': return state + 1; case 'DECREASE': return state - 1; default: return state; } } const {createStore} = Redux; const store = createStore(counter); store.subscribe(() => { setCount(store.getState()); }); function setCount (count) { document.getElementById('value').innerHTML = count; } document.getElementById('btn_increase').addEventListener('click', function () { store.dispatch({type: 'INCREASE'}); }); document.getElementById('btn_decrease').addEventListener('click', function () { store.dispatch({type: 'DECREASE'}); });