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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 |
<!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>Demo app Count with use ReactJS and Redux</title> </head> <body> <div id="root"></div> <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.1.0/redux.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.4/react-redux.js"></script> <script src="https://cdn.jsdelivr.net/npm/@reduxjs/[email protected]/dist/redux-toolkit.umd.min.js"></script> <!-- =========== slices/count_slice.js =========== --> <script> //1. Khai báo Slice: Dùng RTK.createSlice khai báo tất cả State, Reducers và Actions luôn const countSlice = RTK.createSlice({ name: 'count', initialState: { number: 1, loading: false }, reducers: { action_increment(state, action) { state.number += action.payload.amount; }, action_decrement(state, action) { state.number -= action.payload.amount; }, action_increment_saga_request(state, action) { state.loading = true; }, action_increment_saga_success(state, action) { state.loading = false; state.number += action.payload.amount; }, } }); // Export ra các actions, reducer tương ứng :D const countReducer = countSlice.reducer; const { action_increment, action_decrement, action_increment_saga_request, action_increment_saga_success } = countSlice.actions; </script> <!-- =========== src/api/count.js =========== --> <script> // Thunk - Middleware: Các action dạng bất đồng bộ thì sẽ xử lý tại đây // Tại button, ta dispatch 1 function có dạng trả về là 1 async function // async function này có nhiệm vụ giải quyết các promise, sau đó mới dispatch action thật const increment_async = (payload) => async (dispatch) => { let promise = (data) => new Promise((resolve, reject) => { setTimeout(() => { resolve(data); }, 1000); }) let response = await promise(payload); dispatch(action_increment(response)); } </script> <!-- =========== src/middleware/saga.js =========== --> <script> // Saga.0: Ta giả lập 1 cái promise như sau: const promise_count = (n) => new Promise((resolve, reject) => { setTimeout(() => { resolve(n); }, 2000); }) // //Saga.5: Khai báo Saga worker: Những thằng handle saga còn lại có nhiệm vụ worker const handle_increment_saga = function* (action) { let response = yield promise_count(action.payload); // Có thể delay bằng cách // yield delay(2000); // put ==> kích hoạt action :D, đi hết middleware 1 vòng rồi đó yield ReduxSaga.effects.put(action_increment_saga_success(response)) } //Saga.4: Khai báo Saga watcher: Thằng này chỉ có nhiệm vụ đón các action và giao nhiệm vụ cho các saga khác const countSaga = function* () { //Các effect creator hay gặp: takeEvery, takeLatest, takeLeading yield ReduxSaga.effects.takeEvery(action_increment_saga_request().type, handle_increment_saga) } const otherSaga = function* () { // console.log("Other saga"); // RootSaga sẽ khởi chạy tất cả các saga khác lần đầu tiên khi khởi động } // Saga.3: Khai báo rootSaga const rootSaga = function* () { yield ReduxSaga.effects.all([countSaga(), otherSaga()]) } </script> <!-- =========== src/store.js =========== --> <script type="text/babel"> // 2. Saga.1: Khai báo sagaMiddleware (xem thêm trên trang chủ cách khai báo khi sử dụng npm install) const sagaMiddleware = ReduxSaga.default(); // Saga.2: Khai báo store sử dụng middleware Saga //configureStore: mặc định đã có "thunk" const store = RTK.configureStore({ reducer: { count: countReducer }, middleware: getDefaultMiddleware => getDefaultMiddleware().concat(sagaMiddleware), //sài thêm "sagaMiddleware" }) // Saga.3: Khởi chạy rootSaga sau khi được mount vào Store sagaMiddleware.run(rootSaga); </script> <!-- =========== components/App.js =========== --> <script type="text/babel"> function App(props) { //3. Dùng useSelector và useDispatch để làm việc với store của Redux const count = ReactRedux.useSelector(state => state.count); const dispatch = ReactRedux.useDispatch(); return ( <div> <p> {count.number} {count.loading && <img src="https://vcdn-ione.vnecdn.net/2016/07/13/loading-256-0001-4566-1468383063.gif" width="12px" />} </p> <button onClick={() => { dispatch(action_increment({ amount: 1 })) }}>Increase</button> <button onClick={() => { dispatch(action_decrement({ amount: 1 })) }}>Decrease</button><br /> <button onClick={() => { dispatch(increment_async({ amount: 1 })) }}>Increase Thunk</button><br /> <button onClick={() => { dispatch(action_increment_saga_request({ amount: 1 })) }}>Increase Saga takeEvery</button> </div> ) } </script> <!-- =========== src/index.js =========== --> <script type="text/babel"> //4. Connect React và Redux bằng Provider, với store=store đã được khai báo ở trên const Provider = ReactRedux.Provider; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); </script> </body> </html> |
Demo-Count: 8. use Redux-Toolkit, Redux-Saga: Effect Creator
Author: admin - Posted: 28/06/21 - Update: 28/06/21