Các kiến thức trong Project này gồm có:
- Sử dụng Class: props, state, event
- Redux: Reducers, actions, container components
- Storage
- Protypes
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 291 292 293 294 295 296 297 298 299 300 301 302 303 304 |
<!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', }; </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.student.id) { let new_student = { id: uuid.s16(), username: action.student.username, email: action.student.email, }; new_state.push(new_student); } else { let find_student = new_state.find((item) => item.id == action.student.id); find_student.username = action.student.username; find_student.email = action.student.email; } localStorage.setItem('listStudent', JSON.stringify(new_state)); return new_state; case types.DELETE_STUDENT: new_state = state.filter((item) => item.id != action.id); localStorage.setItem('listStudent', JSON.stringify(new_state)); return new_state; } 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) => { return { type: types.SAVE_STUDENT, student: student, }; }; let action_deleteStudent = (id) => { return { type: types.DELETE_STUDENT, id: id, }; }; </script> <!-- =========== components/App.js =========== --> <script type="text/babel"> class App extends React.Component { constructor(props) { super(props); this.state = { txtFilterName: '', student: {}, }; } updateState_student = (e) => { let updateStudent = this.state.student; updateStudent[e.target.name] = e.target.value; this.setState({ student: updateStudent, }); }; onFilterStudent = (e) => { e.preventDefault(); this.setState({ txtFilterName: e.target.value, }); }; onNewStudent = (e) => { e.preventDefault(); this.setState({ student: {}, }); }; onEditStudent = (e, student) => { e.preventDefault(); this.setState({ student: { ...student }, }); }; onSaveStudent = (e) => { e.preventDefault(); if (!this.state.student.username || !this.state.student.email) return; this.props.dispatch_saveStudent(this.state.student); //reset state sau khi save xong this.setState({ student: {}, }); }; onDeleteStudent = (e, id) => { e.preventDefault(); this.props.dispatch_deleteStudent(id); }; render() { // console.log(this.props); let filter = this.state.txtFilterName; let tr_listStudent = this.props.listStudent .filter((item) => item.username.includes(filter)) .map((item, index) => { return ( <tr key={item.id}> <td>{index}</td> <td>{item.username}</td> <td>{item.email}</td> <td> <button onClick={(e) => this.onEditStudent(e, item)}>Sửa</button> <button onClick={(e) => this.onDeleteStudent(e, item.id)}>Xóa</button> </td> </tr> ); }); return ( <div> <button onClick={this.onNewStudent}>New Student</button> <br /> <input type="text" placeholder="username" name="username" value={this.state.student.username} onChange={this.updateState_student} /> <br /> <input type="text" placeholder="email" name="email" value={this.state.student.email} onChange={this.updateState_student} /> <br /> <button onClick={this.onSaveStudent}> {this.state.student.id ? 'Update Student' : 'Add Student'} </button> <br /> <br /> <input type="text" placeholder="Search ..." name="txtFilterName" value={this.state.txtFilterName} onChange={this.onFilterStudent} /> <table> <thead> <tr> <th>#</th> <th>Username</th> <th>Email</th> <th>Action</th> </tr> </thead> <tbody>{tr_listStudent}</tbody> </table> </div> ); } } </script> <!-- =========== container/AppContainer.js =========== --> <script type="text/babel"> //Dùng riêng 1 class Container chỉ để mục đích hứng các props từ Redux //Các props hứng được từ Redux lại chuyển tiếp về Component class AppContainer extends React.Component { render() { return ( <App listStudent={this.props.listStudent} product={this.props.product} dispatch_saveStudent={this.props.dispatch_saveStudent} dispatch_deleteStudent={this.props.dispatch_deleteStudent} /> ); } } //check dữ liệu nhận từ store (props) bằng propTypes AppContainer.propTypes = { listStudent: PropTypes.arrayOf( PropTypes.shape({ username: PropTypes.string, email: PropTypes.string, }) ).isRequired, }; //mapStateToProps: chuyển state từ store thành props của component let mapStateToProps_App = (state) => { return { listStudent: state.listStudent, product: state.product, }; }; //mapDispatchToProps: chuyển action từ store thành props của component let mapDispatchToProps_App = (dispatch, props) => { return { dispatch_saveStudent: (student) => { dispatch(action_saveStudent(student)); }, dispatch_deleteStudent: (id) => { dispatch(action_deleteStudent(id)); }, }; }; //connect Component Container với Redux bằng connect let AppConnect = ReactRedux.connect(mapStateToProps_App, mapDispatchToProps_App)(AppContainer); </script> <!-- =========== src/store.js =========== --> <script type="text/babel"> //Gọi store bằng reducers, cái đoạn lằng nhằng là để sử dụng cho redux chrome extensions //const store = Redux.createStore(rootReducer); const store = Redux.createStore( rootReducer /* preloadedState, */, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() ); </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( //Lúc này, không còn gọi class App nữa, mà gọi AppContainer là Appconnect <Provider store={store}> <AppConnect /> </Provider>, document.getElementById('root') ); </script> </body> </html> |