*** Redux gồm 5 phần chính
- Khai báo State
- Khai báo Reducer (dựa trên State)
- Khai báo action
- Khai báo Store (dựa trên Reducer)
- Dispatch action --> thay đổi state
- Subscribe --> hành động khi state thay đổi
- Redux không nhất thiết phải dùng với ReactJS, có thể dùng với VueJS thoải mái
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Redux without React</title> </head> <body> <button id="btnIncrement">Increment</button> <button id="btnDecrement">Decrement</button> <p id="txtCount"></p> <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.1.0/redux.js"></script> <script> const txtCount = document.getElementById("txtCount"); const btnIncrement = document.getElementById("btnIncrement"); const btnDecrement = document.getElementById("btnDecrement"); const { createStore, combineReducers } = window.Redux; //1. Khai báo state const initialState = { amount: 1 } //2. Khai báo Reducer const countReducer = (state = initialState, action) => { let newState = { ...state } switch (action.type) { case 'INCREMENT': { newState.amount += action.payload.amount return newState } case 'DECREMENT': { newState.amount -= action.payload.amount return newState } default: return state; } } //3. Khai báo action const action_increment = (payload) => ({ type: 'INCREMENT', payload: payload, }) const action_decrement = (payload) => ({ type: 'DECREMENT', payload: payload, }) //4. Khai báo store (rootReducer: bao gồm nhiều Reducer) const rootReducer = combineReducers({ count: countReducer, }) const store = createStore(rootReducer); //5. Dispatch Action btnIncrement.onclick = () => { store.dispatch(action_increment({ amount: 1 })) } btnDecrement.onclick = () => { store.dispatch(action_decrement({ amount: 1 })) } //...Render lần đầu txtCount.innerText = store.getState().count.amount; //... Subscribe state khi state thay đổi store.subscribe(() => { txtCount.innerText = store.getState().count.amount; }) </script> </body> </html> |