|
| 1 | +<!DOCTYPE html> |
| 2 | +<html> |
| 3 | + <head> |
| 4 | + <title>Redux basic example</title> |
| 5 | + <script src="https://npmcdn.com/redux@latest/dist/redux.min.js"></script> |
| 6 | + </head> |
| 7 | + <body> |
| 8 | + <div> |
| 9 | + <p> |
| 10 | + Clicked: <span id="value">0</span> times |
| 11 | + <button id="increment">+</button> |
| 12 | + <button id="decrement">-</button> |
| 13 | + <button id="incrementIfOdd">Increment if odd</button> |
| 14 | + <button id="incrementAsync">Increment async</button> |
| 15 | + </p> |
| 16 | + </div> |
| 17 | + <script> |
| 18 | + function counter(state, action) { |
| 19 | + if (typeof state === 'undefined') { |
| 20 | + return 0 |
| 21 | + } |
| 22 | + |
| 23 | + switch (action.type) { |
| 24 | + case 'INCREMENT': |
| 25 | + return state + 1 |
| 26 | + case 'DECREMENT': |
| 27 | + return state - 1 |
| 28 | + default: |
| 29 | + return state |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + var store = Redux.createStore(counter) |
| 34 | + var valueEl = document.getElementById('value') |
| 35 | + |
| 36 | + function render() { |
| 37 | + valueEl.innerHTML = store.getState().toString() |
| 38 | + } |
| 39 | + |
| 40 | + render() |
| 41 | + store.subscribe(render) |
| 42 | + |
| 43 | + document.getElementById('increment') |
| 44 | + .addEventListener('click', function () { |
| 45 | + store.dispatch({ type: 'INCREMENT' }) |
| 46 | + }) |
| 47 | + |
| 48 | + document.getElementById('decrement') |
| 49 | + .addEventListener('click', function () { |
| 50 | + store.dispatch({ type: 'DECREMENT' }) |
| 51 | + }) |
| 52 | + |
| 53 | + document.getElementById('incrementIfOdd') |
| 54 | + .addEventListener('click', function () { |
| 55 | + if (store.getState() % 2 === 1) { |
| 56 | + store.dispatch({ type: 'INCREMENT' }) |
| 57 | + } |
| 58 | + }) |
| 59 | + |
| 60 | + document.getElementById('incrementAsync') |
| 61 | + .addEventListener('click', function () { |
| 62 | + setTimeout(function () { |
| 63 | + store.dispatch({ type: 'INCREMENT' }) |
| 64 | + }, 1000) |
| 65 | + }) |
| 66 | + </script> |
| 67 | + </body> |
| 68 | +</html> |
0 commit comments