Heim  >  Artikel  >  Web-Frontend  >  Was ist Redux und wie können wir es nutzen?

Was ist Redux und wie können wir es nutzen?

WBOY
WBOYOriginal
2024-08-29 11:03:34891Durchsuche

Was ist Redux und wie verwenden wir es? Redux ist wie ein hilfreiches Tool zum Verwalten des Status von JavaScript-Programmen. Es hilft, alles organisiert zu halten und erleichtert die Arbeit. Betrachten Sie es als eine Möglichkeit, den Überblick über die Vorgänge in Ihrem Programm zu behalten und sicherzustellen, dass alles stabil bleibt.

Grundsätzlich kann Redux problemlos mit verschiedenen JavaScript-Bibliotheken oder Frameworks wie React, Angular oder Vue zusammenarbeiten. Dadurch können sie ihre Aufgaben noch besser bewältigen. Deshalb ist es für Webentwickler äußerst wichtig, etwas über Redux zu lernen.

In diesem Artikel werden wir über die Grundlagen von Redux sprechen. Wir erklären, was es ist, warum Menschen es verwenden und wie es funktioniert. Wir werden uns wichtige Teile wie Store, Actions und Reducers ansehen, die die Bausteine ​​von Redux sind. Das Lernen und Investieren in Redux-Schulungen ist für Webentwickler sehr wichtig.

Was ist Redux und warum wird es verwendet?

Eine häufig gestellte Frage zu Redux ist, warum Menschen es verwenden. Also, was ist der Grund? Nun, Redux ist wirklich wertvoll für die Verwaltung des Status von Anwendungen, insbesondere wenn diese komplexer werden. Nehmen wir das Beispiel einer E-Commerce-Website mit verschiedenen Teilen wie einem Warenkorb, einem Benutzerprofil usw.

Konzentrieren wir uns zum besseren Verständnis auf den Warenkorb-Teil. Es ist dafür verantwortlich, die Anzahl der Artikel im Warenkorb des Benutzers anzuzeigen. Sein Status umfasst alle hinzugefügten Elemente und deren Gesamtzahl. Diese Informationen müssen ständig aktualisiert und dem Benutzer genau angezeigt werden.

Wenn ein Benutzer Artikel hinzufügt oder entfernt, muss das Programm diese Aktionen intern verarbeiten, den Status des Warenkorbs aktualisieren und Änderungen in der Benutzeroberfläche widerspiegeln.

Anfangs funktioniert die Statusverwaltung innerhalb separater Komponenten gut, aber wenn das Programm komplexer wird, wird es notwendig, den Status zwischen Komponenten für Aufgaben wie Anzeige, Aktualisierungen oder die Ausführung von Logik basierend auf gemeinsam genutzten Daten zu teilen. Hier glänzt Redux und liefert die wichtigste Antwort auf die Frage, warum Redux verwendet wird.

Redux fungiert als zentralisierte Zustandsverwaltungsbibliothek und verwaltet den Zustand des Programms. Es stellt wesentliche APIs zum Ändern und Zugreifen auf den aktuellen Status bereit und vereinfacht effektiv den Prozess der Verwaltung mehrerer Status über verschiedene Komponenten hinweg.

Was macht Redux vorhersehbar?

Was Redux in Bezug auf Vorhersehbarkeit auszeichnet, ist die strikte Einhaltung des Prinzips der staatlichen Unveränderlichkeit. In Redux erfordert die Änderung des Anwendungsstatus das Auslösen einer bestimmten Art von Aktion, die die gewünschten Änderungen genau spezifiziert. Diese Aktionen werden dann von Reduzierern verarbeitet, deren Aufgabe ausschließlich darin besteht, den aktuellen Status und die aktuelle Aktion zu verarbeiten und eine neue und aktualisierte Statusinstanz zu erzeugen. Reduzierer ändern den Zustand nicht direkt; Stattdessen erstellen sie eine neue Zustandsinstanz, die die notwendigen Änderungen enthält.

Wie Redux-Erfinder Dan Abramov sagte:

Aktionen können aufgezeichnet und später wiedergegeben werden, wodurch eine konsistente Zustandsverwaltung gewährleistet wird.

Um dieses Konzept zu veranschaulichen und genau zu verstehen, was Redux ist, betrachten wir ein Beispiel aus einem Online-Shop. Wenn der Warenkorb anfänglich 0 Artikel enthält, erhöht das Hinzufügen eines Produkts die Artikelanzahl auf 1. Durch Wiederholen dieser Aktion wird die Artikelanzahl weiter erhöht, sodass ein vorhersehbares Ergebnis gewährleistet ist.

Durch die konsequente Erzeugung desselben Endzustands basierend auf dem Anfangszustand und einer bestimmten Abfolge von Aktionen garantiert Redux Vorhersehbarkeit. Im nächsten Abschnitt werden wir uns eingehender mit den Schlüsselkomponenten von Redux befassen.

Die Kernkomponenten von Redux sind:

What is Redux, and how can we use it?

Um besser zu verstehen, was Redux ist und wie es funktioniert, schauen wir uns seine Schlüsselkomponenten an. Im Wesentlichen besteht Redux aus den folgenden drei Teilen:

**1. Speichern

  1. Aktion
  2. Reduzierer**

Was ist der Store in Redux?

Der Store in Redux fungiert als zentrales Repository für den globalen Status der Anwendung, organisiert in einer hierarchischen Baumstruktur. Es ist wichtig, den Redux Store als einzige Quelle für den Status der Anwendung zu betrachten.

Durch die Integration des Stores in die Hauptkomponente (z. B. App.js) mithilfe der Provider-Komponente erhalten alle untergeordneten Komponenten in der Anwendung Zugriff auf den global gespeicherten Status im Redux Store. Dadurch entsteht praktisch eine Art global zugänglicher Zustand in der gesamten Anwendung. Das folgende Beispiel veranschaulicht dieses Konzept:

`// 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.

Der Statusparameter hat den Standardwert initialCartState, damit der Reduzierer Szenarien verarbeiten kann, in denen er zum ersten Mal mit einem undefinierten Status aufgerufen wird. Jeder Reduzierer muss den Standardstatus verarbeiten. Wenn keine Aktionstypen übereinstimmen, wird der aktuelle Status zurückgegeben. Dadurch wird sichergestellt, dass der Status bei der Auslösung unabhängiger Aktionen unverändert bleibt.

Wenn eine Aktion ausgelöst wird, wird der entsprechende Reduzierer basierend auf dem Aktionstyp aufgerufen. Wenn in unserem Beispiel auf die Schaltfläche „In den Warenkorb“ geklickt wird, löst der Aktionsersteller addItemToCart eine Aktion vom Typ ADD_ITEM_TO_CART aus.

Dann verarbeitet cartReducer diese Aktion, indem es ihren Typ abgleicht. Wenn es mit ADD_ITEM_TO_CART übereinstimmt, aktualisiert es den Status, indem es den noOfItemInCart-Wert erhöht und entsprechend einen neuen Artikel zum Warenkorb-Array hinzufügt.

Es ist wichtig zu beachten, dass Redux Unveränderlichkeit erzwingt, sodass Reduzierer eine neue Kopie des Status mit den erforderlichen Änderungen erstellen, anstatt den vorhandenen Status direkt zu ändern.

Nachdem der Reduzierer den Status aktualisiert hat, werden die Änderungen angezeigt. Nach dem Hinzufügen eines neuen Artikels zum Warenkorb enthält der aktualisierte Status beispielsweise den erhöhten Wert von noOfItemInCart und den neu hinzugefügten Artikel im Warenkorb-Array. Dieser strukturierte Ansatz gewährleistet vorhersehbare Statusaktualisierungen und sorgt für Konsistenz bei der Statusverwaltung in Redux-Anwendungen.

What is Redux, and how can we use it?

Redux und seine Bedeutung lernen

Redux orientiert sich an drei Grundprinzipien:

  1. Zentralisierte Statusverwaltung: Der gesamte Anwendungsstatus wird in einem einzigen, zentralen Speicher gespeichert und in einer einzigartigen baumartigen Struktur organisiert.
  2. Aktionsgesteuerte Statusaktualisierungen: Statusänderungen werden durch das Auslösen von Aktionen initiiert, bei denen es sich um Objekte handelt, die beschreiben, was in der Anwendung passiert ist.
  3. Zustandstransformation über Reduzierer: Reduzierer bestimmen, wie der Zustandsbaum auf Aktionen reagiert, wodurch vorhersehbare Aktualisierungen gewährleistet und die Zustandskonsistenz aufrechterhalten wird.

Das obige ist der detaillierte Inhalt vonWas ist Redux und wie können wir es nutzen?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn