搜尋
首頁web前端js教程什麼是 Redux,我們要如何使用它?

什麼是 Redux,我們要如何使用它? Redux 就像是管理 JavaScript 程式狀態的有用工具。它有助於讓一切井井有條,並使其更易於使用。將其視為追蹤程序中發生的情況並確保一切保持穩定的一種方式。

基本上,Redux 可以與不同的 JavaScript 函式庫或框架(如 React、Angular 或 Vue)順利運作。這使他們能夠更好地管理自己所做的事情。這就是為什麼學習 Redux 對 Web 開發人員來說非常重要。

在本文中,我們將討論 Redux 的基礎知識。我們將解釋它是什麼、人們為什麼使用它以及它是如何運作的。我們將討論 Store、Actions 和Reducers 等重要部分,它們是 Redux 的構建塊。對於 Web 開發人員來說,學習和投資 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 視為應用程式狀態的唯一來源至關重要。

透過使用 Provider 元件將 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></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,這樣reducer就可以處理第一次呼叫時狀態未定義的場景。每個減速器必須處理預設狀態,如果沒有操作類型匹配,則返回當前狀態。這確保了在調度不相關的操作時狀態保持不變。

當一個action被調度時,根據action類型呼叫適當的reducer。在我們的範例中,當按一下「新增至購物車」按鈕時,操作建立者 addItemToCart 會調度 ADD_ITEM_TO_CART 類型的操作。

然後,cartReducer 透過匹配其類型來處理此操作。如果它與 ADD_ITEM_TO_CART 匹配,則會透過增加 noOfItemInCart 值並相應地將新商品新增至購物車陣列來更新狀態。

需要注意的是,Redux 強制執行不變性,因此減速器會建立狀態的新副本並進行必要的更改,而不是直接修改現有狀態。

reducer更新狀態後,變化就會反映出來。例如,將新商品加入購物車後,更新的狀態包括 noOfItemInCart 的遞增值以及購物車陣列中新增的商品。這種結構化方法可確保可預測的狀態更新並保持 Redux 應用程式中管理狀態的一致性。

What is Redux, and how can we use it?

學習Redux及其重要性

Redux 遵循三個關鍵原則:

  1. 集中狀態管理:整個應用程式狀態儲存在單一集中儲存中,並以獨特的樹狀結構組織。
  2. 操作驅動的狀態更新:狀態變更是透過分派作業啟動的,這些操作是描述應用程式中發生的情況的物件。
  3. 透過Reducers進行狀態轉換:Reducers決定狀態樹如何對操作做出反應,確保可預測的更新並保持狀態一致性。

以上是什麼是 Redux,我們要如何使用它?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
使用Next.js(後端集成)構建多租戶SaaS應用程序使用Next.js(後端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:23 AM

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

如何使用Next.js(前端集成)構建多租戶SaaS應用程序如何使用Next.js(前端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:22 AM

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript:探索網絡語言的多功能性JavaScript:探索網絡語言的多功能性Apr 11, 2025 am 12:01 AM

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

JavaScript的演變:當前的趨勢和未來前景JavaScript的演變:當前的趨勢和未來前景Apr 10, 2025 am 09:33 AM

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

神秘的JavaScript:它的作用以及為什麼重要神秘的JavaScript:它的作用以及為什麼重要Apr 09, 2025 am 12:07 AM

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python還是JavaScript更好?Python還是JavaScript更好?Apr 06, 2025 am 12:14 AM

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。1.Python以简洁语法和丰富库生态著称,适用于数据分析和Web开发。2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

如何安裝JavaScript?如何安裝JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript不需要安裝,因為它已內置於現代瀏覽器中。你只需文本編輯器和瀏覽器即可開始使用。 1)在瀏覽器環境中,通過標籤嵌入HTML文件中運行。 2)在Node.js環境中,下載並安裝Node.js後,通過命令行運行JavaScript文件。

在Quartz中如何在任務開始前發送通知?在Quartz中如何在任務開始前發送通知?Apr 04, 2025 pm 09:24 PM

如何在Quartz中提前發送任務通知在使用Quartz定時器進行任務調度時,任務的執行時間是由cron表達式設定的。現�...

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器