** Kiến thức chú ý trong bài:
- Redux: dispatch, action, reducer
- Middleware
- Redux devtools extension
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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
<!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>ReactJS</title> <style> table { border-collapse: collapse; } th, td { padding: 0 0.5rem; border: 1px solid black; } </style> </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> <!-- =========== src/utils.js =========== --> <script> class Uuid { s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } s16() { return this.s4() + this.s4() + this.s4() + this.s4(); } } let uuid = new Uuid(); </script> <!-- =========== constants/ActionTypes.js =========== --> <script> //Các hằng số types ==> sử dụng cho các actions const types = { SAVE_STUDENT: 'SAVE_STUDENT', DELETE_STUDENT: 'DELETE_STUDENT', SET_LIST_STUDENT: 'SET_LIST_STUDENT', }; </script> <!-- =========== reducers/listStudent_reducer.js =========== --> <script> //Trong 1 Reducer bao gồm 2 thành phần: state và reducer //State là nơi chứa dữ liệu //Reducer là nơi xử lý các action (khi bị dispatch) //---- listStudent_state có thể khởi tạo mặc định hoặc lấy trên localStorage let listStudent_state = JSON.parse(localStorage.getItem('listStudent')) || []; let listStudent_reducer = (state = listStudent_state, action) => { //Khi làm việc với state, cần return ra 1 state mới, //Tốt nhất nên copystate cũ luôn let new_state = [...state] switch (action.type) { case types.SAVE_STUDENT: if (!action.payload.id) { let new_student = { id: uuid.s16(), username: action.payload.username, email: action.payload.email, }; new_state.push(new_student); } else { let find_student = new_state.find((item) => item.id == action.payload.id); find_student.username = action.payload.username; find_student.email = action.payload.email; } localStorage.setItem('listStudent', JSON.stringify(new_state)); return new_state; case types.DELETE_STUDENT: new_state = state.filter((item) => item.id != action.payload); localStorage.setItem('listStudent', JSON.stringify(new_state)); return new_state; case types.SET_LIST_STUDENT: localStorage.setItem('listStudent', JSON.stringify(action.payload)); return action.payload; } return new_state; }; </script> <!-- =========== reducers/listproduct_Reducer.js =========== --> <!-- =========== reducers/index.js =========== --> <script> //Combine nhiều Reducers lại để tạo ra 1 Reducer duy nhất let rootReducer = Redux.combineReducers({ listStudent: listStudent_reducer, //product: productReducer, }); </script> <!-- =========== actions/index.js =========== --> <script> //Các action khi được dispatch ==> sẽ trả về object actions tương ứng let action_saveStudent = (student) => ({ type: types.SAVE_STUDENT, payload: student, }); let action_deleteStudent = (id) => ({ type: types.DELETE_STUDENT, payload: id, }); let action_setListStudent = (list) => ({ type: types.SET_LIST_STUDENT, payload: list, }) // Trường hợp action là 1 function get api (không trả về 1 object nữa) // ==> Giải quyết bằng cách dùng middleware ==> Từ action này lại dispatch 1 action khác let action_getAllStudent = () => async (dispatch) => { let url = 'https://fakestoreapi.com/users?limit=10'; let response = await fetch(url); let responseJSON = await response.json(); dispatch(action_setListStudent(responseJSON)); }; </script> <!-- =========== middleware/list_middleware.js =========== --> <script> //Khi action là 1 function get api (không phải là 1 object như bình thường, cần phải xử lý qua middleware) const processFunctionMiddleware = store => next => action => { if (typeof action === 'function') { // Vì action_getAllStudent là 1 hàm, nên cần truyền lại dispatch vào hàm đó để sử dụng // Câu lệnh này sẽ khởi chạy được đoạn: "dispatch(action_setListStudent(list));" return action(next) } // Nếu action không trả về 1 function, thì chắc là nó trả về 1 object, nếu thế thì cho nó đi tiếp luôn :D return next(action); } //Middleware là việc kiểm tra và xử lý các action trước ==> convert các action đúng ý mình trước đã, rồi mới cho đi tiếp const checkSymbolMiddleware = store => next => action => { //console.log(store, next, action, store.getState()); if (action.type == types.SAVE_STUDENT && action.payload.username.includes("fuck")) { action.payload.username = action.payload.username.replaceAll("fuck", "****") } //next: tương đương với "dispatch" ==> next(action) tương đương dispatch(action)==>nghĩa là chạy bình thường return next(action); } </script> <!-- =========== src/store.js =========== --> <script type="text/babel"> // Cái đoạn lằng nhằng là để sử dụng cho redux chrome extensions const composeEnhancers = typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize... }) : Redux.compose; // Gọi store bằng reducers(basic): const store = Redux.createStore(rootReducer); // Ném các middleware vào trong Redux.applyMiddleware() const store = Redux.createStore( rootReducer /* preloadedState, */, composeEnhancers(Redux.applyMiddleware(processFunctionMiddleware, checkSymbolMiddleware)) ); </script> <!-- =========== components/App.js =========== --> <script type="text/babel"> function App(props) { const { listStudent, dispatch_saveStudent, dispatch_deleteStudent, dispatch_getAllStudent } = props; const [filterName, setFilterName] = React.useState(''); const [student, setStudent] = React.useState({ username: '', email: '', id: '' }); const updateState_student = (e) => { let newStudent = { ...student }; newStudent[e.target.name] = e.target.value; setStudent(newStudent) }; const onSaveStudent = (e) => { if (!student.username || !student.email) return; dispatch_saveStudent(student); //reset state sau khi save xong setStudent({ username: '', email: '', id: '' }); }; return ( <div> <button onClick={() => { setStudent({ username: '', email: '', id: '' }) }}>New Student</button> <br /> <input type="text" placeholder="username" name="username" value={student.username} onChange={updateState_student} /> <br /> <input type="text" placeholder="email" name="email" value={student.email} onChange={updateState_student} /> <br /> <button onClick={onSaveStudent}> {student.id ? 'Update Student' : 'Add Student'} </button> <br /> <br /> <input type="text" placeholder="Search ..." name="txtFilterName" value={filterName} onChange={e => { setFilterName(e.target.value) }} /> <table> <thead> <tr> <th>#</th> <th>Username</th> <th>Email</th> <th>Action</th> </tr> </thead> <tbody> { listStudent .filter((item) => item.username.includes(filterName)) .map((item, index) => { return ( <tr key={item.id}> <td>{index}</td> <td>{item.username}</td> <td>{item.email}</td> <td> <button onClick={e => { setStudent({ ...item }) }}>Sửa</button> <button onClick={e => { dispatch_deleteStudent(item.id) }}>Xóa</button> </td> </tr> ); }) } </tbody> </table> <button onClick={e => { dispatch_getAllStudent() }}>Get Student Online</button> </div> ); } </script> <!-- =========== container/AppContainer.js =========== --> <script type="text/babel"> //Dùng riêng 1 HOC mục đích chỉ để hứng các props từ Redux //Các props hứng được từ Redux lại chuyển tiếp về Component //mapStateToProps: chuyển state từ store thành props của component let mapStateToProps_App = (state) => ({ listStudent: state.listStudent, }) //mapDispatchToProps: chuyển action từ store thành props của component let mapDispatchToProps_App = (dispatch, props) => ({ dispatch_saveStudent: (student) => { dispatch(action_saveStudent(student)); }, dispatch_deleteStudent: (id) => { dispatch(action_deleteStudent(id)); }, dispatch_getAllStudent: () => { dispatch(action_getAllStudent()); }, }) //connect Component Container với Redux bằng connect với 2 biến là props: mapStateToProps, mapDispatchToProps let AppConnect = ReactRedux.connect(mapStateToProps_App, mapDispatchToProps_App)(App); </script> <!-- =========== src/index.js =========== --> <script type="text/babel"> //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}> <AppConnect /> </Provider>, document.getElementById('root') ); </script> </body> </html> |