javascript / expert
Snippet
Deterministische State Machines mit useReducer
Die Verwendung von useReducer zur Implementierung einer endlichen Zustandsmaschine stellt sicher, dass Ihre Anwendung vorhersehbar zwischen Zuständen wechselt. Durch das Mapping erlaubter Übergänge verhindern Sie unmögliche Zustände und vereinfachen komplexe Logik.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const initialState = { status: 'idle', data: null, error: null };function fetchReducer(state, action) {const transitions = {idle: { FETCH: { status: 'loading' } },loading: { RESOLVE: { status: 'success', data: action.data }, REJECT: { status: 'failure', error: action.error } },success: { FETCH: { status: 'loading' } },failure: { FETCH: { status: 'loading' } }};const nextState = transitions[state.status][action.type];return nextState ? { ...state, ...nextState } : state;}const [state, dispatch] = React.useReducer(fetchReducer, initialState);
react
Erklärung
1
const transitions = { ... }
Eine Lookup-Tabelle, die definiert, welche Aktionen für jeden aktuellen Zustand gültig sind.
2
return nextState ? { ...state, ...nextState } : state;
Stellt sicher, dass der Status nur aktualisiert wird, wenn der Übergang explizit definiert ist.