Flux
Flux nima?
Section titled “Flux nima?”Flux — bu Facebook tomonidan React ilovalari uchun ishlab chiqilgan arxitektura patterni. Uning asosiy g’oyasi — Unidirectional Data Flow (Bir tomonlama ma’lumot oqimi). Bu MVC dagi murakkab va chalkash ma’lumot oqimlarini oldini olishga yordam beradi.
Flux 4 ta asosiy qismdan iborat:
- Actions: Tizimda sodir bo’ladigan hodisalar (masalan,
ADD_TODO). - Dispatcher: Barcha actionlarni qabul qilib, ro’yxatdan o’tgan Store larga tarqatuvchi markaziy xab (hub).
- Stores: Ma’lumotlar (State) va logikani saqlaydi.
- Views: React komponentlari (UI).
Ishlash tartibi (Flow)
Section titled “Ishlash tartibi (Flow)”Flux da ma’lumot faqat bitta yo’nalishda harakatlanadi:
graph LR Action --> Dispatcher Dispatcher --> Store Store --> View View -- "Trigger Action" --> Action- View foydalanuvchi harakati natijasida Action yaratadi.
- Action Dispatcher ga yuboriladi.
- Dispatcher uni barcha Store larga tarqatadi.
- Store o’ziga kerakli action ni ushlab olib, o’z holatini (state) yangilaydi va o’zgarish haqida xabar beradi (emit change).
- View (Controller-View) o’zgarishni eshitib, o’zini yangilaydi.
Redux va Flux
Section titled “Redux va Flux”Ko’pchilik Flux ni Redux orqali taniydi. Redux — bu Flux g’oyasining eng mashhur implementatsiyasi, lekin u biroz soddalashtirilgan (yagona Store, Dispatcher yo’q).
Amaliy Misol (Redux uslubida)
Section titled “Amaliy Misol (Redux uslubida)”// Action Typesconst ADD_TODO = "ADD_TODO";
// Action Creatorfunction addTodo(text) { return { type: ADD_TODO, payload: text };}
// Reducer (Store logikasi)function todoReducer(state = [], action) { switch (action.type) { case ADD_TODO: return [...state, action.payload]; default: return state; }}
// Storefunction createStore(reducer) { let state = reducer(undefined, {}); const listeners = [];
return { getState: () => state, dispatch: (action) => { state = reducer(state, action); listeners.forEach((fn) => fn()); }, subscribe: (fn) => listeners.push(fn), };}
// Foydalanishconst store = createStore(todoReducer);store.subscribe(() => console.log("State:", store.getState()));store.dispatch(addTodo("Birinchi vazifa"));store.dispatch(addTodo("Ikkinchi vazifa"));// State: ["Birinchi vazifa"]// State: ["Birinchi vazifa", "Ikkinchi vazifa"]