Middle
Kāda ir Flux galvenā koncepcija?
sobes.tech AI
Atbilde no AI
Galvenā Flux koncepcija ir vienvirziena datu plūsma (unidirectional data flow). Programmas stāvoklis tiek glabāts vienā vietā (Store), un tā izmaiņas ir iespējamas tikai caur Dispatcher, kas apstrādā Actions.
Flux galvenie elementi:
- Actions: Apraksta, kas noticis programmā (piemēram, "lietotājs nospieda pogu"). Tie satur darbības tipu un nesošo slodzi (payload) ar datiem.
- Dispatcher: Vienīgā ieejas punkts visiem Actions. Pārsūta Actions uz Store.
- Store: Satur noteiktas programmas daļas stāvokli un loģiku tā izmaiņām, atbildot uz Actions. Store emitē notikumus par stāvokļa izmaiņām (Change Event).
- Views: Lietotāja interfeisa attēlojums. Parāda stāvokli no Store. Reaģē uz Store izmaiņām un atjaunojas atbilstoši. View tieši nemaina stāvokli, bet izveido Actions.
Datu plūsma:
- Lietotājs mijiedarbojas ar View.
- View izveido Action.
- Action tiek nosūtīts uz Dispatcher.
- Dispatcher pārsūta Action uz Store.
- Store apstrādā Action, maina savu stāvokli un emitē Change Event.
- View, kas ir pierakstītas uz Store, saņem Change Event un atjaunojas, attēlojot jauno stāvokli.
// Piemērs ar Action
const addTodoAction = (text) => ({
type: 'ADD_TODO',
payload: {
text: text
}
});
// Piemērs ar Dispatcher (vienkāršots)
class Dispatcher {
register(callback) {
this.callbacks.push(callback);
}
dispatch(action) {
this.callbacks.forEach(callback => callback(action));
}
}
// Piemērs ar Store (vienkāršots)
class TodoStore {
constructor(dispatcher) {
this.todos = [];
dispatcher.register(this.handleAction.bind(this));
}
handleAction(action) {
switch (action.type) {
case 'ADD_TODO':
this.todos.push(action.payload.text);
this.emitChange();
break;
// citi gadījumi
}
}
getAll() {
return this.todos;
}
// Metodes abonēšanai un atcelšanai
addChangeListener(callback) { /* ... */ }
removeChangeListener(callback) { /* ... */ }
emitChange() { /* ... */ }
}
// Piemērs ar View (vienkāršots)
class TodoList extends React.Component {
componentDidMount() {
this.store.addChangeListener(this.updateState);
}
componentWillUnmount() {
this.store.removeChangeListener(this.updateState);
}
updateState() {
this.setState({ todos: this.store.getAll() });
}
handleAddTodo(text) {
this.dispatcher.dispatch(addTodoAction(text));
}
render() {
// Darba saraksta un ievades lauka attēlojums
}
}
Flux nodrošina prognozējamu stāvokļa pārvaldību un atvieglo kļūdu meklēšanu, jo datu plūsma ir skaidra un kontrolējama.