|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="zh"> |
| 3 | +<head> |
| 4 | + <meta charset="UTF-8"> |
| 5 | + <title>Redux</title> |
| 6 | +</head> |
| 7 | +<body> |
| 8 | + |
| 9 | +<div> |
| 10 | + <button id="sub">减少</button> |
| 11 | + <span id="ageSpan">1</span> |
| 12 | + <button id="add">增加</button> |
| 13 | + <button id="addFive">加5</button> |
| 14 | +</div> |
| 15 | + |
| 16 | +<script src="https://unpkg.com/redux@4.2.0/dist/redux.js"></script> |
| 17 | + |
| 18 | +<script> |
| 19 | +/** |
| 20 | + * 1. 创建reducer整合函数 |
| 21 | + * 2. 通过reducer对象创建store |
| 22 | + * 3. 对store中的state进行订阅 |
| 23 | + * 4. 通过dispatch派发state的操作指令 |
| 24 | + */ |
| 25 | + |
| 26 | +const subBtn = document.getElementById('sub'); |
| 27 | +const addBtn = document.getElementById('add'); |
| 28 | +const ageSpan = document.getElementById('ageSpan'); |
| 29 | +const addFiveBtn = document.getElementById('addFive'); |
| 30 | + |
| 31 | +// 1. 创建reducer整合函数 |
| 32 | +// state表示当前状态,用于生成新状态 action保存操作信息的对象 |
| 33 | +function reducer(state = { age: 18, name: 'sunshine'}, action) { |
| 34 | + switch (action.type) { |
| 35 | + case 'ADD': |
| 36 | + return { ...state, age: state.age + 1 }; |
| 37 | + case 'SUB': |
| 38 | + return { ...state, age: state.age - 1 }; |
| 39 | + case 'ADD_N': |
| 40 | + return { ...state, age: state.age + action.payload }; |
| 41 | + default: |
| 42 | + return state; |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +// 2. 通过reducer对象创建store |
| 47 | +// const store = Redux.createStore(reducer); |
| 48 | +const store = Redux.createStore(reducer, { name: 'victor', age: 30 }); |
| 49 | + |
| 50 | +// 3. 对store中的state进行订阅 |
| 51 | +store.subscribe(() => { |
| 52 | + console.log(store.getState()); |
| 53 | + console.log(store.getState().name); |
| 54 | + ageSpan.innerText = store.getState().age; |
| 55 | +}); |
| 56 | + |
| 57 | +// 4. 通过dispatch派发state的操作指令 |
| 58 | +subBtn.addEventListener('click', () => { |
| 59 | + store.dispatch({type: 'SUB'}); |
| 60 | +}); |
| 61 | +addBtn.addEventListener('click', () => { |
| 62 | + store.dispatch({type: 'ADD'}); |
| 63 | +}); |
| 64 | +addFiveBtn.addEventListener('click', () => { |
| 65 | + store.dispatch({type: 'ADD_N', payload: 5}); |
| 66 | +}); |
| 67 | +</script> |
| 68 | + |
| 69 | +</body> |
| 70 | +</html> |
0 commit comments