」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 什麼是 Redux,我們要如何使用它?

什麼是 Redux,我們要如何使用它?

發佈於2024-11-08
瀏覽:943

What is Redux, and how do we use it? Redux is like a helpful tool for managing the state of JavaScript programs. It helps keep everything organized and makes it easier to work with. Think of it as a way to keep track of what's happening in your program and make sure everything stays stable.

Basically, Redux can work smoothly with different JavaScript libraries or frameworks like React, Angular, or Vue. It makes them even better at managing the stuff they do. That's why learning about Redux is super important for web developers.

In this article, we're going to talk about the basics of Redux. We'll explain what it is, why people use it, and how it works. We'll look at important parts like Store, Actions, and Reducers, which are the building blocks of Redux. Making learning and investing in Redux training highly important for web developers.

What is Redux and Why Use It?

One common question about Redux is why people use it. So, what's the reason? Well, Redux is really valuable for managing the state of applications, especially when they get more complex. Let's take the example of an e-commerce website with different parts like a shopping cart, user profile, etc.

Let's focus on the shopping cart part for a better understanding. It's responsible for showing the number of items in the user's cart. Its state includes all the items added and their total count. This information needs to be constantly updated and accurately displayed to the user.

When a user adds or removes items, the program needs to handle these actions internally, update the cart's state, and reflect changes in the user interface.

Initially, managing state within separate components works fine, but as the program grows more complex, sharing state between components for tasks like display, updates, or executing logic based on shared data becomes necessary. This is where Redux shines and provides the main answer to why Redux is used.

Redux acts as a centralized state management library, handling the program's state. It provides essential APIs for changing and accessing the current state and effectively simplifies the process of managing multiple states across different components.

What makes Redux predictable?

What distinguishes Redux in terms of predictability is its strict adherence to the principle of state immutability. In Redux, changing the state of the application requires dispatching a certain type of action that precisely specifies the desired changes. These actions are then processed by reducers, whose task is solely to handle the current state and action, producing a new and updated state instance. Reducers do not directly modify the state; instead, they create a new state instance that incorporates the necessary changes.

As stated by Redux creator Dan Abramov:

actions can be recorded and replayed later, ensuring consistent state management.

To illustrate this concept and to precisely understand what Redux is, let's consider an example from an online store. If the shopping cart initially holds 0 items, adding a product increases the item count to 1. Repeating this action further increases the item count, ensuring a predictable outcome.

By consistently producing the same final state based on the initial state and a specific sequence of actions, Redux guarantees predictability. In the next section, we'll delve deeper into the key components of Redux.

The core components of Redux are:

What is Redux, and how can we use it?

To better understand what Redux is and how it works, let's explore its key components. Essentially, Redux consists of the following three parts:

**1. Store

  1. Action
  2. Reducer**

What is the Store in Redux?

The Store in Redux acts as a centralized repository for the global state of the application, organized in a hierarchical tree structure. It's crucial to consider the Redux Store as the sole source for the application's state.

By integrating the Store into the main component (e.g., App.js) using the Provider component, all child components in the application gain access to the globally stored state within the Redux Store. This effectively creates a type of globally accessible state throughout the application. The following example illustrates this concept:

`// 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(
    // Wrapping the App component with the Provider component and passing the Redux store as a prop
      // Rendering the main App component
  
)`

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,
    }
  };
};
`
`const dispatch = useDispatch(); const addItemToCart = () => { return { type: "ADD_ITEM_TO_CART", payload: { bookName: "Harry Potter and the Goblet of Fire", noOfItem: 1, } }; }; `

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:

`const dispatch = useDispatch();

const addItemToCart = () => {
  return {
    type: "ADD_ITEM_TO_CART",
    payload: {
      bookName: "Harry Potter and the Goblet of Fire",
      noOfItem: 1,
    }
  };
};
`
`// 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 dispatch = useDispatch();

const addItemToCart = () => {
  return {
    type: "ADD_ITEM_TO_CART",
    payload: {
      bookName: "Harry Potter and the Goblet of Fire",
      noOfItem: 1,
    }
  };
};
`
`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.

The state parameter has a default value, initialCartState, so that the reducer can handle scenarios where it is called for the first time with an undefined state. Each reducer must handle the default state, where if no action types match, it returns the current state. This ensures that the state remains unchanged in case of dispatching unrelated actions.

When an action is dispatched, the appropriate reducer is called based on the action type. In our example, when the "Add to Cart" button is clicked, the action creator addItemToCart dispatches an action of type ADD_ITEM_TO_CART.

Then, cartReducer processes this action by matching its type. If it matches ADD_ITEM_TO_CART, it updates the state by incrementing the noOfItemInCart value and adding a new item to the cart array accordingly.

It's important to note that Redux enforces immutability, so reducers create a new copy of the state with the necessary changes instead of directly modifying the existing state.

After updating the state by the reducer, the changes reflect. For example, after adding a new item to the cart, the updated state includes the incremented value of noOfItemInCart and the newly added item in the cart array. This structured approach ensures predictable state updates and maintains consistency in managing state in Redux applications.

What is Redux, and how can we use it?

Learning Redux and its importance

Redux is guided by three key principles:
  1. Centralized State Management: The entire application state is stored in a single, centralized store, organized in a unique tree-like structure.
  2. Action-Driven State Updates: State changes are initiated by dispatching actions, which are objects describing what happened in the application.
  3. State Transformation via Reducers: Reducers dictate how the state tree reacts to actions, ensuring predictable updates and maintaining state consistency.

版本聲明 本文轉載於:https://dev.to/drlaravel/what-is-redux-and-how-can-we-use-it-51m3?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 如何在Ajax資料載入過程中顯示進度條?
    如何在Ajax資料載入過程中顯示進度條?
    如何在Ajax 資料載入期間顯示進度條處理使用者觸發的事件(例如從下拉方塊中選擇值)時,通常會使用非同步擷取資料阿賈克斯。在獲取數據時,向用戶提供正在發生某事的視覺指示是有益的。本文探討了一種在 Ajax 請求期間顯示進度條的方法。 使用 Ajax 實作進度條要建立一個準確追蹤 Ajax 呼叫進度的...
    程式設計 發佈於2024-11-08
  • 如何在 PHP 中透過 SSH 安全連接到遠端 MySQL 伺服器?
    如何在 PHP 中透過 SSH 安全連接到遠端 MySQL 伺服器?
    在PHP 中透過SSH 安全連接到遠端MySQL 伺服器要為PHP 資料庫連線建立安全隧道,以下SSH 隧道解決方案提供了一種強大的方法。 SSH 隧道設定建立通往 MySQL 資料庫伺服器的 SSH 隧道。為此,請使用以下命令:ssh -fNg -L 3307:10.3.1.55:3306 [em...
    程式設計 發佈於2024-11-08
  • 混淆技術真的可以保護可執行檔免受逆向工程的影響嗎?
    混淆技術真的可以保護可執行檔免受逆向工程的影響嗎?
    保護可執行檔免於逆向工程:解決方案有限的挑戰保護程式碼免於未經授權的逆向工程是開發人員持續關注的問題,尤其是當它包含敏感資訊時。雖然已經提出了各種方法,但重要的是要承認完全防止逆向工程實際上是不可能的。 常見混淆技術使用者建議的策略,例如程式碼注入、混淆和自訂啟動例程的目的是使反彙編變得不那麼簡單。...
    程式設計 發佈於2024-11-08
  • 掌握 Laravel 中的 Eloquent where 條件
    掌握 Laravel 中的 Eloquent where 條件
    Laravel 的 Eloquent ORM(物件關係映射)是其突出的功能之一,提供了與資料庫互動的強大而富有表現力的方式。 Eloquent 提供的一項基本功能是方法,它允許開發人員高效、直觀地過濾查詢。在本文中,我們將深入研究 where 條件,探索其各種形式和實際用例。 w...
    程式設計 發佈於2024-11-08
  • 在 Gmail 的 Chrome 12+ 更新中如何從剪貼簿貼上圖片?
    在 Gmail 的 Chrome 12+ 更新中如何從剪貼簿貼上圖片?
    將剪貼簿中的圖像貼到Gmail:Chrome 12 中的操作方法Google 宣布能夠將剪貼簿中的圖像直接貼到Gmail使用Chrome 12 的Gmail 引發了人們對其底層機制的好奇。儘管使用了最新的 Chrome 版本,但一些用戶仍然無法找到有關如何在 Webkit 中實現此增強功能的資訊。 ...
    程式設計 發佈於2024-11-08
  • JavaScript 示範場景競賽 - JS 版
    JavaScript 示範場景競賽 - JS 版
    JS1024 於 2024 年回歸! 準備好迎接令人興奮的挑戰! JS1024 回歸,透過在 JavaScript、HTML 或 GLSL 中創建令人驚嘆的演示(全部在 1024 位元組限制內),將開發人員推向極限。無論您是經驗豐富的編碼員還是新手,這都是您展示創造力和技術技能的機...
    程式設計 發佈於2024-11-08
  • 第九屆 TCmeeting 的更新
    第九屆 TCmeeting 的更新
    議程上有幾個項目,本文重點介紹第 104 次 TC39 會議 [2024 年 10 月 8 日至 10 日] 的功能提案及其進展。 第一階段: 表示度量:建議在 JavaScript 中使用適當的單位格式化和表示度量。 Immutable ArrayBuffers:新增 Arra...
    程式設計 發佈於2024-11-08
  • 如何使用 CSS 在圖像地圖上實現滑鼠懸停效果?
    如何使用 CSS 在圖像地圖上實現滑鼠懸停效果?
    使用 CSS 設定圖片地圖滑鼠懸停樣式使用 CSS 設定圖片地圖滑鼠懸停樣式建立互動網頁時,通常需要包含具有可點擊區域的圖像。通常,這是使用圖像映射來實現的。然而,事實證明,在滑鼠懸停時設置這些區域的樣式以提供額外的互動性是難以實現的。 <img src="{main_photo}&...
    程式設計 發佈於2024-11-08
  • 升級您的前端遊戲:無頭與靜態未來的學習框架
    升級您的前端遊戲:無頭與靜態未來的學習框架
    前端領域正以驚人的速度發展。忘掉笨重、單一的網站吧-未來屬於無頭 CMS 和靜態網站產生器 (SSG)。這些時尚的強大功能提供了無與倫比的速度、靈活性和安全性,但征服它們需要使用正確的工具。 為了利用他們的力量,開發人員正在轉向 Next.js 和 Gatsby,這兩個尖端的前端框架塑造了我們如何...
    程式設計 發佈於2024-11-08
  • 如何修復 PyGame 動畫閃爍:故障排除和解決方案
    如何修復 PyGame 動畫閃爍:故障排除和解決方案
    PyGame 動畫閃爍:故障排除和解決方案在執行 PyGame 程式時,您可能會遇到動畫閃爍的問題。這可能會令人沮喪,特別是如果您不熟悉使用該框架。 PyGame 中動畫閃爍的根本原因通常是多次呼叫 pygame.display.update()。不應在應用程式循環中的多個點更新顯示,而應僅在循環結...
    程式設計 發佈於2024-11-08
  • JavaScript 中的聲明式程式設計與命令式程式設計
    JavaScript 中的聲明式程式設計與命令式程式設計
    當談到程式設計方法時,經常會出現兩種常見的方法:聲明式程式設計和命令式程式設計。每個都有其優點和理想的用例,尤其是在 JavaScript 中。讓我們透過一些例子來探討這兩種風格。 命令式程式設計:告訴電腦如何做 命令式程式設計就像是給出一組詳細的指令。你告訴計算機如何一步一步達到...
    程式設計 發佈於2024-11-08
  • 掌握 NestJS 中的資料驗證:類別驗證器和類別轉換器的完整指南
    掌握 NestJS 中的資料驗證:類別驗證器和類別轉換器的完整指南
    Introduction In the fast-paced world of development, data integrity and reliability are paramount. Robust data validation and efficient handl...
    程式設計 發佈於2024-11-08
  • 有多少 Python 套件的版本控制正確?
    有多少 Python 套件的版本控制正確?
    前幾天,當我研究Python套件中的漏洞資料庫時,我意識到其中的一些套件版本無法輕鬆解析並與其他版本字串進行比較,因為它們不遵守Python 版本控制- 舊的PEP 440或取代它的版本說明符規範。所以我開始想知道這種情況有多普遍。 Python 套件索引上有多少套件實際上有有效版本? 顯而易見的...
    程式設計 發佈於2024-11-08
  • 如何在 Web 應用程式中有效地對 Ajax 請求進行排序?
    如何在 Web 應用程式中有效地對 Ajax 請求進行排序?
    排序 Ajax 請求在許多 Web 應用程式中,通常會遇到需要迭代集合並對每個元素發出 Ajax 請求的情況。雖然利用非同步請求來避免瀏覽器凍結很誘人,但有效管理這些請求可以防止伺服器過載和其他潛在問題。 jQuery 1.5 對於 jQuery 1.5 及更高版本,$. ajaxQueue() 插...
    程式設計 發佈於2024-11-08
  • JavaScript 中「%」運算子的作用是什麼?
    JavaScript 中「%」運算子的作用是什麼?
    揭開 JavaScript 中 % 運算子的本質JavaScript 中神秘的 % 符號稱為模運算子。它在數學運算中發揮關鍵作用,它會傳回一個運算元除以另一個運算元後的餘數。 模運算子通常表示如下:var1 % var2其中var1 和 var2 代表操作數。 例如,如果我們有表達式 12 % 5,...
    程式設計 發佈於2024-11-08

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3