Szybka pomoc

Ściągawka z Redux

Szybki przewodnik po Redux: tworzenie magazynu Store, czyste funkcje Reducer, Action Creators, dispatch, middleware i hooki React Redux.

· Opublikowano

Redux to przewidywalny kontener stanu dla aplikacji JavaScript oparty na jednokierunkowym przepływie danych.

Podstawowe Koncepcje i Tworzenie Magazynu (Store)

import { createStore } from 'redux';

// Funkcja Reducer: czysta funkcja obliczająca kolejny stan
function counterReducer(state = { value: 0 }, action) {
  switch (action.type) {
    case 'counter/incremented':
      return { value: state.value + 1 };
    case 'counter/decremented':
      return { value: state.value - 1 };
    default:
      return state;
  }
}

// Tworzenie magazynu store
const store = createStore(counterReducer);

// Subskrypcja zmian stanu
const unsubscribe = store.subscribe(() => {
  console.log('Bieżący stan:', store.getState());
});

// Wysyłanie akcji
store.dispatch({ type: 'counter/incremented' }); // { value: 1 }
store.dispatch({ type: 'counter/decremented' }); // { value: 0 }

Kreatory Akcji i Oprogramowanie Pośredniczące (Middleware)

// Kreator akcji (Action Creator)
const incrementBy = (amount) => ({
  type: 'counter/incrementBy',
  payload: amount
});

// Wzorzec middleware (logowanie, asynchroniczne thunki)
const loggerMiddleware = (storeAPI) => (next) => (action) => {
  console.log('Wysyłanie akcji:', action);
  const result = next(action);
  console.log('Kolejny stan:', storeAPI.getState());
  return result;
};

Hooki React Redux (useSelector i useDispatch)

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

export function Counter() {
  const count = useSelector((state) => state.value);
  const dispatch = useDispatch();

  return (
    <div>
      <span>Count: {count}</span>
      <button onClick={() => dispatch({ type: 'counter/incremented' })}>
        +
      </button>
    </div>
  );
}

Nowoczesny Redux Toolkit (RTK)

Nowoczesne aplikacje Redux wykorzystują pakiet Redux Toolkit w celu redukcji powtarzalnego kodu:

import { createSlice, configureStore } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment: (state) => { state.value += 1; },
    decrement: (state) => { state.value -= 1; }
  }
});

export const { increment, decrement } = counterSlice.actions;
export const store = configureStore({ reducer: counterSlice.reducer });

Materiały Źródłowe

Powiązane tematy