首頁  >  文章  >  web前端  >  什麼是 Redux,我們要如何使用它?

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

WBOY
WBOY原創
2024-08-29 11:03:34891瀏覽

什麼是 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 />  // 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