javascript / expert
Snippet
Prototyp-Verknüpfter Objekt-Zustandsautomat für Dynamische React-Abläufe
Demonstriert objektorientierte Prototypen-Vererbung über Object.create, um einen erweiterbaren Zustandsautomaten für React-Zustands-Controller aufzubauen. Übergangsvalidierungen sind in Klassenprototypen gekapselt und garantieren typsichere Ausführungspfade.
snippet.js
javascript
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
import React, { useReducer } from 'react';class BaseState {canTransitionTo(nextState) {return this.allowedTransitions?.includes(nextState) ?? false;}}class IdleState extends BaseState {allowedTransitions = ['loading'];name = 'IDLE';}class LoadingState extends BaseState {allowedTransitions = ['success', 'idle'];name = 'LOADING';}const statePrototypes = {idle: Object.create(new IdleState()),loading: Object.create(new LoadingState()),};function flowReducer(current, action) {const currentState = statePrototypes[current];return currentState.canTransitionTo(action.type) ? action.type : current;}export function PrototypeStateController() {const [state, dispatch] = useReducer(flowReducer, 'idle');return <button onClick={() => dispatch({ type: 'loading' })}>Current: {state}</button>;}
react
Erklärung
1
class BaseState {
Etabliert den Prototyp-Basisvertrag zur Prüfung gültiger Übergangspfade.
2
idle: Object.create(new IdleState()),
Instanziiert prototypen-delegierte Objektinstanzen zur Verwaltung der Verzweigungsauswertung.