۱۴۰۴/۰۸/۰۴ Nebular

redux

ایجاد Action Types

// actions/types.ts
export const INCREMENT = "INCREMENT";
export const DECREMENT = "DECREMENT";
export const RESET = "RESET";

۲️⃣ ایجاد Actions

// actions/counterActions.ts
import { INCREMENT, DECREMENT, RESET } from "./types";

export const increment = () => ({ type: INCREMENT });
export const decrement = () => ({ type: DECREMENT });
export const reset = () => ({ type: RESET });

۳️⃣ ایجاد Reducer

// reducers/counterReducer.ts
import { INCREMENT, DECREMENT, RESET } from "../actions/types";

const initialState = { value: 0 };

export default function counterReducer(state = initialState, action: any) {
  switch (action.type) {
    case INCREMENT:
      return { ...state, value: state.value + 1 };
    case DECREMENT:
      return { ...state, value: state.value - 1 };
    case RESET:
      return { ...state, value: 0 };
    default:
      return state;
  }
}

۴️⃣ ایجاد Store

// store/index.ts
import { createStore, combineReducers } from "redux";
import counterReducer from "../reducers/counterReducer";

const rootReducer = combineReducers({
  counter: counterReducer,
});

export type RootState = ReturnType<typeof rootReducer>;

export const store = createStore(rootReducer);

۵️⃣ اتصال به React

// main.tsx یا index.tsx
import React from "react";
import ReactDOM from "react-dom/client";
import { Provider } from "react-redux";
import { store } from "./store";
import App from "./App";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <Provider store={store}>
    <App />
  </Provider>
);

۶️⃣ استفاده در کامپوننت

import { useSelector, useDispatch } from "react-redux";
import { RootState } from "./store";
import { increment, decrement, reset } from "./actions/counterActions";

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

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
      <button onClick={() => dispatch(reset())}>Reset</button>
    </div>
  );
}

🔹 مقایسه با Redux Toolkit

ویژگیRedux معمولیRedux Toolkit
Boilerplateزیاد (action type, action creator, reducer جدا)کم (createSlice همه چیز رو میسازه)
Immutabilityباید دستی با spread operator انجام بدیمیتونی mutable بنویسی، toolkit خودش immutable می‌کنه
راحتیسخت‌تر و verboseساده و concise
Learning curveبالاترپایین‌تر
Accept Cookies
Accept Cookies
[your-shortcode]