>  기사  >  웹 프론트엔드  >  Redux는 무엇이며 어떻게 사용할 수 있나요?

Redux는 무엇이며 어떻게 사용할 수 있나요?

WBOY
WBOY원래의
2024-08-29 11:03:34896검색

Redux란 무엇이며 어떻게 사용하나요? Redux는 JavaScript 프로그램의 상태를 관리하는 데 유용한 도구와 같습니다. 모든 것을 정리하는 데 도움이 되고 작업하기가 더 쉬워집니다. 프로그램에서 일어나는 일을 추적하고 모든 것이 안정적으로 유지되도록 하는 방법이라고 생각하세요.

기본적으로 Redux는 React, Angular, Vue와 같은 다양한 JavaScript 라이브러리나 프레임워크와 원활하게 작동할 수 있습니다. 이는 그들이 하는 일을 더욱 효과적으로 관리할 수 있게 해줍니다. 그렇기 때문에 Redux에 대해 배우는 것이 웹 개발자에게 매우 중요합니다.

이번 글에서는 Redux의 기본에 대해 이야기해보겠습니다. 우리는 그것이 무엇인지, 왜 사람들이 그것을 사용하는지, 그리고 어떻게 작동하는지 설명할 것입니다. Redux의 구성 요소인 Store, Actions, Reducers와 같은 중요한 부분을 살펴보겠습니다. 웹 개발자에게는 Redux 교육에 대한 학습과 투자가 매우 중요합니다.

Redux는 무엇이고 왜 사용하는가?

Redux에 대한 일반적인 질문 중 하나는 사람들이 Redux를 사용하는 이유입니다. 그렇다면 이유는 무엇입니까? 음, Redux는 특히 애플리케이션이 더 복잡해질 때 애플리케이션 상태를 관리하는 데 정말 유용합니다. 장바구니, 사용자 프로필 등 다양한 부분으로 구성된 전자상거래 웹사이트를 예로 들어보겠습니다.

이해를 돕기 위해 장바구니 부분을 중심으로 살펴보겠습니다. 사용자 장바구니에 있는 항목 수를 표시하는 역할을 담당합니다. 상태에는 추가된 모든 항목과 총 개수가 포함됩니다. 이 정보는 지속적으로 업데이트되어야 하며 사용자에게 정확하게 표시되어야 합니다.

사용자가 항목을 추가하거나 제거하면 프로그램은 이러한 작업을 내부적으로 처리하고 장바구니 상태를 업데이트하며 사용자 인터페이스의 변경 사항을 반영해야 합니다.

처음에는 별도의 구성 요소 내에서 상태를 관리하는 것이 잘 작동하지만 프로그램이 더욱 복잡해짐에 따라 공유 데이터를 기반으로 표시, 업데이트 또는 논리 실행과 같은 작업을 위해 구성 요소 간에 상태를 공유하는 것이 필요해졌습니다. Redux가 빛을 발하는 곳이자 Redux가 사용되는 이유에 대한 주요 답변을 제공하는 곳입니다.

Redux는 프로그램 상태를 처리하는 중앙 집중식 상태 관리 라이브러리 역할을 합니다. 현재 상태를 변경하고 액세스하는 데 필수적인 API를 제공하며 다양한 구성 요소에서 여러 상태를 관리하는 프로세스를 효과적으로 단순화합니다.

Redux를 예측 가능하게 만드는 것은 무엇입니까?

예측 가능성 측면에서 Redux의 차별점은 상태 불변성 원칙을 엄격하게 준수한다는 것입니다. Redux에서 애플리케이션 상태를 변경하려면 원하는 변경 사항을 정확하게 지정하는 특정 유형의 작업을 전달해야 합니다. 그런 다음 이러한 작업은 현재 상태와 작업만 처리하여 새롭고 업데이트된 상태 인스턴스를 생성하는 리듀서에 의해 처리됩니다. 리듀서는 상태를 직접 수정하지 않습니다. 대신 필요한 변경 사항을 통합하는 새로운 상태 인스턴스를 생성합니다.

Redux 제작자 Dan Abramov가 언급한 바와 같이:

나중에 작업을 기록하고 재생할 수 있어 일관된 상태 관리가 보장됩니다.

이 개념을 설명하고 Redux가 무엇인지 정확하게 이해하기 위해 온라인 상점의 예를 살펴보겠습니다. 처음에 장바구니에 항목이 0개 있는 경우 제품을 추가하면 항목 수가 1로 증가합니다. 이 작업을 반복하면 항목 수가 더 늘어나 예측 가능한 결과가 보장됩니다.

Redux는 초기 상태와 특정 작업 순서를 기반으로 동일한 최종 상태를 일관되게 생성함으로써 예측 가능성을 보장합니다. 다음 섹션에서는 Redux의 주요 구성 요소에 대해 더 자세히 살펴보겠습니다.

Redux의 핵심 구성 요소는 다음과 같습니다.

What is Redux, and how can we use it?

Redux가 무엇이고 어떻게 작동하는지 더 잘 이해하기 위해 핵심 구성 요소를 살펴보겠습니다. 기본적으로 Redux는 다음 세 부분으로 구성됩니다.

**1. 매장

  1. 액션
  2. 리듀서**

Redux의 Store란 무엇인가요?

Redux의 Store는 계층적 트리 구조로 구성된 애플리케이션의 전역 상태에 대한 중앙 집중식 저장소 역할을 합니다. Redux Store를 애플리케이션 상태의 유일한 소스로 간주하는 것이 중요합니다.

공급자 구성 요소를 사용하여 Store를 기본 구성 요소(예: App.js)에 통합하면 애플리케이션의 모든 하위 구성 요소가 Redux Store 내에 전역적으로 저장된 상태에 액세스할 수 있습니다. 이는 애플리케이션 전반에 걸쳐 전역적으로 액세스 가능한 상태 유형을 효과적으로 생성합니다. 다음 예에서는 이 개념을 보여줍니다.

`// src/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'  // Importing the Provider component from 'react-redux'
import { App } from './App'  // Importing the main App component
import createStore from './createReduxStore'  // Importing the function to create the Redux store

const store = createStore()  // Creating the Redux store using the createStore function

// As of React 18
const root = ReactDOM.createRoot(document.getElementById('root'))  // Creating a root element to render the React app
root.render(
  <Provider store={store}>  // Wrapping the App component with the Provider component and passing the Redux store as a prop
    <App />  // Rendering the main App component
  </Provider>
)`

What is Redux, and how can we use it?

The above code snippet initializes the Redux Store using the createStore function and then integrates it into the React application by wrapping the main App component with the Provider component. As a result, the Redux Store becomes accessible to all components of the application.

The entire state of the application is structured as a kind of JavaScript object tree within the Redux Store. As illustrated below:

`// Example of the structure of the store object
{
    noOfItemInCart: 2,  // Represents the total number of items in the cart
    cart: [  // Represents an array containing details of each item in the cart
        {
            bookName: "Harry Potter and the Chamber of Secrets",  // Name of the book
            noOfItem: 1,  // Quantity of this book in the cart
        },
        {
            bookName: "Harry Potter and the Prisoner of Azkaban",  // Name of another book
            noOfItem: 1  // Quantity of this book in the cart
        }
    ]
}`

In the above example, the Redux Store has two main features:

noOfItemInCart: Indicates the total number of items in the cart.
cart: An array containing objects, each representing a specific item in the cart. Each object includes properties such as bookName, which represents the name of the book, and noOfItem, which indicates the quantity of that book in the cart.
This structured representation enables efficient management and access to the application's state, facilitating seamless updates and interactions within the program.

What is an action in Redux?

Actions in Redux are essential for changing the application's state. They are JavaScript objects that describe what has happened in the application. As mentioned earlier, Redux enforces the idea of immutable state and prevents direct changes through views or network calls. Instead, any state changes must be communicated through actions.

Let's consider a scenario with a sample store containing two books, each with one copy. Now, imagine a user wants to add another item to their cart. They click on the "Add to Cart" button next to the desired item.

Upon clicking, a type of action is dispatched. This action, represented as a JavaScript object, reflects the necessary changes in the store. The following example illustrates this concept:

`const dispatch = useDispatch();

const addItemToCart = () => {
  return {
    type: "ADD_ITEM_TO_CART",
    payload: {
      bookName: "Harry Potter and the Goblet of Fire",
      noOfItem: 1,
    }
  };
};
<button onClick={() => dispatch(addItemToCart())}>Add to cart</button>`

In the above example, the addItemToCart function acts as an action creator. When called, it generates an action object that describes the intention to add a specific book to the cart. This action includes a type property indicating the type of action ("ADD_ITEM_TO_CART") and a payload containing the details of the book to be added.

This structured approach ensures transparency and consistency in state management, facilitating effective communication of state changes throughout the application.

For a better understanding of actions in Redux:

To better understand what actions are and what role they play in Redux, let's slightly complicate the previous example. In Redux, each action must have a type property that specifies the type of dispatched operation. While additional details can be included in the action object, they are optional and vary depending on the specific action being dispatched. For example, consider the action created by addItemToCart in the previous example:

`// Action created by the addItemToCart action creator

{
    type: "ADD_ITEM_TO_CART", // Note: Every action must have a type key
    payload: {
        bookName: "Harry Potter and the Goblet of Fire",
        noOfItem: 1,
    }
}`

In the above example, the action type or action ADD_ITEM_TO_CART indicates the intention to add items to the cart. Additionally, the payload property contains specific details about the added item, such as its name and other relevant details.

What are Reducers in Reducers?

What is Redux, and how can we use it?

This uniform structure in managing actions ensures consistency and allows reducers to accurately interpret and process the dispatched actions. As a result, it facilitates effective state management in Redux.

Reducers in Redux are another essential part, but what exactly are reducers and what do they do? Reducers are essentially functions responsible for changing the application state based on dispatched actions. They adhere to the principle of immutability, meaning they don't directly alter the current state; instead, they return a new updated state.

In essence, reducers receive two parameters: the previous state and an action. They then process this information to indicate a new state representing the current state of the application.

In larger applications, there may be multiple reducers, each managing different parts or sections of the global state. For example, one reducer might manage the shopping cart state, while another handles user details.

When an action is dispatched, all reducers are called. Each reducer examines the action using a switch statement to identify its type. Upon finding a match, the corresponding reducer performs necessary updates to the state and returns a new instance of the global state.

For a better understanding of reducers in Redux:

To better grasp what reducers are and their role in Redux, let's consider the following example:

`const initialCartState = {   
    noOfItemInCart: 0,         
    cart: []                             
}

// NOTE:
// It is important to pass an initial state as default to
// the state parameter to handle the case of calling
// the reducers for the first time when the
// state might be undefined

const cartReducer = (state = initialCartState, action) => {
    switch (action.type) {
        case "ADD_ITEM_TO_CART":
            return {
                ...state,
                noOfItemInCart: state.noOfItemInCart + 1,
                cart : [
                    ...state.cart,
                    action.payload
                ]
            }
        case "DELETE_ITEM_FROM_CART":
            return {
                // Remaining logic
            }
        default:
            return state 
    }       // Important to handle the default behaviour
}           // either by returning the whole state as it is
            // or by performing any required logic`

In the above example, we created a reducer called cartReducer, which is a JavaScript function. This function accepts two parameters.

state 매개변수에는 기본값인initialCartState가 있으므로 리듀서가 정의되지 않은 상태로 처음 호출되는 시나리오를 처리할 수 있습니다. 각 리듀서는 기본 상태를 처리해야 하며, 일치하는 작업 유형이 없으면 현재 상태를 반환합니다. 이렇게 하면 관련 없는 작업을 디스패치하는 경우에도 상태가 변경되지 않고 유지됩니다.

액션이 전달되면 액션 유형에 따라 적절한 감속기가 호출됩니다. 이 예에서는 "장바구니에 추가" 버튼을 클릭하면 작업 생성자 addItemToCart가 ADD_ITEM_TO_CART 유형의 작업을 전달합니다.

그런 다음 cartReducer는 해당 유형을 일치시켜 이 작업을 처리합니다. ADD_ITEM_TO_CART와 일치하는 경우 noOfItemInCart 값을 증가시키고 이에 따라 장바구니 배열에 새 항목을 추가하여 상태를 업데이트합니다.

Redux는 불변성을 적용하므로 리듀서는 기존 상태를 직접 수정하는 대신 필요한 변경 사항이 포함된 상태의 새 복사본을 생성한다는 점에 유의하는 것이 중요합니다.

리듀서에서 상태를 업데이트한 후 변경 사항이 반영됩니다. 예를 들어 장바구니에 새 항목을 추가한 후 업데이트된 상태에는 noOfItemInCart의 증가된 값과 장바구니 배열에 새로 추가된 항목이 포함됩니다. 이러한 구조화된 접근 방식은 예측 가능한 상태 업데이트를 보장하고 Redux 애플리케이션에서 상태 관리의 일관성을 유지합니다.

What is Redux, and how can we use it?

Redux 학습과 그 중요성

Redux는 세 가지 주요 원칙을 따릅니다.

  1. 중앙 집중식 상태 관리: 전체 애플리케이션 상태는 고유한 트리 구조로 구성된 단일 중앙 저장소에 저장됩니다.
  2. 액션 기반 상태 업데이트: 상태 변경은 애플리케이션에서 발생한 일을 설명하는 객체인 액션을 전달하여 시작됩니다.
  3. 리듀서를 통한 상태 변환: 리듀서는 상태 트리가 작업에 반응하는 방식을 지시하여 예측 가능한 업데이트를 보장하고 상태 일관성을 유지합니다.

위 내용은 Redux는 무엇이며 어떻게 사용할 수 있나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.