hoc-lap-trinh-4

Redux là một thư viện quản lý trạng thái cho các ứng dụng JavaScript, thường được sử dụng với các thư viện như React hoặc Angular để xây dựng giao diện người dùng. Redux giúp bạn quản lý trạng thái của toàn bộ ứng dụng một cách có cấu trúc và dễ kiểm soát.

Dưới đây là một số khái niệm chính trong Redux:

1.Store: Nơi lưu trữ trạng thái của ứng dụng. Store là một đối tượng chứa toàn bộ trạng thái của ứng dụng và chỉ có một store duy nhất trong một ứng dụng Redux.

2. Actions: Các hành động là các đối tượng JavaScript đơn giản có thuộc tính type và có thể có thêm dữ liệu bổ sung. Chúng mô tả những gì đã xảy ra trong ứng dụng. Ví dụ:

const incrementAction = { type: 'INCREMENT' };
const addTodoAction = { type: 'ADD_TODO', payload: { text: 'Learn Redux' } };

3. Reducers: Các hàm thuần túy nhận vào trạng thái hiện tại và một action, sau đó trả về trạng thái mới. Reducers xác định cách trạng thái ứng dụng thay đổi để phản ứng với một action nào đó.

function counterReducer(state = { count: 0 }, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

4. Dispatch: Phương thức để gửi một action đến store. Khi một action được dispatch, store sẽ sử dụng reducers để cập nhật trạng thái.

store.dispatch({ type: 'INCREMENT' });

Selectors: Các hàm được sử dụng để lấy dữ liệu từ store một cách có tổ chức và tách biệt.

Redux giúp việc quản lý trạng thái trở nên dễ dàng hơn, đặc biệt là trong các ứng dụng phức tạp với nhiều thành phần và luồng dữ liệu không đồng bộ.

Ví dụ React Redux cho state loading

Để tạo ví dụ về React Redux quản lý trạng thái loading sử dụng TypeScript, chúng ta sẽ thực hiện các bước sau:

  1. Kết nối Redux với React component và quản lý trạng thái loading.

2. Cài đặt các thư viện cần thiết.

3. Thiết lập cấu trúc dự án.

4. Tạo các action, reducer và store.

Bước 1: Cài đặt các thư viện cần thiết

Chạy lệnh sau để cài đặt React, Redux và các thư viện liên quan:

npm install react redux react-redux @reduxjs/toolkit @types/react-redux typescript

Bước 2: Thiết lập cấu trúc dự án

Tạo cấu trúc thư mục như sau:

src/
  ├── actions/
  │   └── loadingActions.ts
  ├── reducers/
  │   └── loadingReducer.ts
  ├── store/
  │   └── index.ts
  ├── components/
  │   └── LoadingComponent.tsx
  └── App.tsx
  └── index.tsx

Bước 3: Tạo các action, reducer và store

actions/loadingActions.ts

export const START_LOADING = 'START_LOADING';
export const STOP_LOADING = 'STOP_LOADING';

interface StartLoadingAction {
  type: typeof START_LOADING;
}

interface StopLoadingAction {
  type: typeof STOP_LOADING;
}

export type LoadingActionTypes = StartLoadingAction | StopLoadingAction;

export const startLoading = (): LoadingActionTypes => ({
  type: START_LOADING,
});

export const stopLoading = (): LoadingActionTypes => ({
  type: STOP_LOADING,
});

reducers/loadingReducer.ts

import { LoadingActionTypes, START_LOADING, STOP_LOADING } from '../actions/loadingActions';

interface LoadingState {
  isLoading: boolean;
}

const initialState: LoadingState = {
  isLoading: false,
};

const loadingReducer = (state = initialState, action: LoadingActionTypes): LoadingState => {
  switch (action.type) {
    case START_LOADING:
      return { isLoading: true };
    case STOP_LOADING:
      return { isLoading: false };
    default:
      return state;
  }
};

export default loadingReducer;

store/index.ts

import { configureStore } from '@reduxjs/toolkit';
import loadingReducer from '../reducers/loadingReducer';

const store = configureStore({
  reducer: {
    loading: loadingReducer,
  },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

export default store;

Bước 4: Kết nối Redux với React component và quản lý trạng thái loading

components/LoadingComponent.tsx

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { RootState, AppDispatch } from '../store';
import { startLoading, stopLoading } from '../actions/loadingActions';

const LoadingComponent: React.FC = () => {
  const dispatch: AppDispatch = useDispatch();
  const isLoading = useSelector((state: RootState) => state.loading.isLoading);

  const handleStartLoading = () => {
    dispatch(startLoading());
  };

  const handleStopLoading = () => {
    dispatch(stopLoading());
  };

  return (
    <div>
      <h1>{isLoading ? 'Loading...' : 'Not Loading'}</h1>
      <button onClick={handleStartLoading}>Start Loading</button>
      <button onClick={handleStopLoading}>Stop Loading</button>
    </div>
  );
};

export default LoadingComponent;

App.tsx

import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import LoadingComponent from './components/LoadingComponent';

const App: React.FC = () => {
  return (
    <Provider store={store}>
      <LoadingComponent />
    </Provider>
  );
};

export default App;

Đến đây, bạn đã tạo một ứng dụng React Redux đơn giản để quản lý trạng thái loading sử dụng TypeScript. Ứng dụng này gồm có một component hiển thị trạng thái loading và các nút để bắt đầu và dừng loading.

By hoadv

Leave a Reply

Your email address will not be published. Required fields are marked *