Redux とは何ですか? どのように使用できますか?

WBOY
リリース: 2024-08-29 11:03:34
オリジナル
889 人が閲覧しました

Redux とは何ですか?また、どのように使用しますか? Redux は、JavaScript プログラムの状態を管理するための便利なツールのようなものです。すべてを整理整頓し、作業を容易にするのに役立ちます。これは、プログラム内で何が起こっているかを追跡し、すべてが安定していることを確認する方法と考えてください。

基本的に、Redux は、React、Angular、Vue などのさまざまな JavaScript ライブラリやフレームワークとスムーズに連携できます。そうすることで、自分のやるべきことをより上手に管理できるようになります。だからこそ、Web 開発者にとって Redux について学ぶことが非常に重要です。

この記事では、Redux の基本について説明します。それが何であるか、人々がそれを使用する理由、そしてそれがどのように機能するかについて説明します。 Redux の構成要素であるストア、アクション、リデューサーなどの重要な部分を見ていきます。 Web 開発者にとって、Redux トレーニングへの学習と投資は非常に重要です。

Redux とは何ですか? なぜ Redux を使用するのですか?

Redux に関するよくある質問の 1 つは、なぜ Redux を使用するのかということです。それで、その理由は何ですか? Redux は、特にアプリケーションがより複雑になった場合に、アプリケーションの状態を管理するのに非常に役立ちます。ショッピング カート、ユーザー プロフィールなどのさまざまな部分を備えた電子商取引 Web サイトの例を見てみましょう。

理解を深めるために、ショッピング カートの部分に注目してみましょう。ユーザーのカート内の商品数を表示する役割を果たします。その状態には、追加されたすべての項目とその合計数が含まれます。この情報は常に更新され、ユーザーに正確に表示される必要があります。

ユーザーがアイテムを追加または削除すると、プログラムはこれらのアクションを内部で処理し、カートの状態を更新し、変更をユーザー インターフェイスに反映する必要があります。

最初は、個別のコンポーネント内での状態管理は問題なく機能しますが、プログラムが複雑になるにつれて、表示、更新、または共有データに基づくロジックの実行などのタスクのためにコンポーネント間で状態を共有することが必要になります。ここが 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 は次の 3 つの部分で構成されます:

**1.ストア

  1. アクション
  2. 減速機**

Redux のストアとは何ですか?

Redux のストアは、階層ツリー構造で編成された、アプリケーションのグローバル状態の集中リポジトリとして機能します。 Redux ストアをアプリケーションの状態の唯一のソースとして考慮することが重要です。

プロバイダーコンポーネントを使用してストアをメインコンポーネント (App.js など) に統合すると、アプリケーション内のすべての子コンポーネントが Redux ストア内にグローバルに保存された状態にアクセスできるようになります。これにより、アプリケーション全体でグローバルにアクセス可能な一種の状態が効果的に作成されます。次の例は、この概念を示しています:

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

Parameter keadaan mempunyai nilai lalai, initialCartState, supaya pengurang boleh mengendalikan senario di mana ia dipanggil buat kali pertama dengan keadaan tidak ditentukan. Setiap pengurang mesti mengendalikan keadaan lalai, di mana jika tiada jenis tindakan sepadan, ia mengembalikan keadaan semasa. Ini memastikan bahawa keadaan kekal tidak berubah sekiranya menghantar tindakan yang tidak berkaitan.

Apabila tindakan dihantar, pengurang yang sesuai dipanggil berdasarkan jenis tindakan. Dalam contoh kami, apabila butang "Tambah ke Troli" diklik, pencipta tindakan addItemToCart menghantar tindakan jenis ADD_ITEM_TO_CART.

Kemudian, cartReducer memproses tindakan ini dengan memadankan jenisnya. Jika ia sepadan dengan ADD_ITEM_TO_CART, ia mengemas kini keadaan dengan menambah nilai noOfItemInCart dan menambah item baharu pada tatasusunan troli dengan sewajarnya.

Adalah penting untuk ambil perhatian bahawa Redux menguatkuasakan ketidakbolehubah, jadi pengurang mencipta salinan baharu keadaan dengan perubahan yang diperlukan dan bukannya mengubah suai secara langsung keadaan sedia ada.

Selepas mengemas kini keadaan oleh pengurang, perubahan mencerminkan. Sebagai contoh, selepas menambah item baharu pada troli, keadaan dikemas kini termasuk nilai tambahan noOfItemInCart dan item yang baru ditambah dalam tatasusunan troli. Pendekatan berstruktur ini memastikan kemas kini keadaan yang boleh diramal dan mengekalkan konsistensi dalam mengurus keadaan dalam aplikasi Redux.

What is Redux, and how can we use it?

Pembelajaran Redux dan kepentingannya

Redux dipandu oleh tiga prinsip utama:

  1. Pengurusan Negeri Berpusat: Keseluruhan keadaan aplikasi disimpan dalam stor tunggal berpusat, disusun dalam struktur seperti pokok yang unik.
  2. Kemas Kini Negeri Didorong Tindakan: Perubahan keadaan dimulakan dengan menghantar tindakan, yang merupakan objek yang menerangkan perkara yang berlaku dalam aplikasi.
  3. Transformasi Negeri melalui Pengurang: Pengurang menentukan cara pokok keadaan bertindak balas terhadap tindakan, memastikan kemas kini yang boleh diramal dan mengekalkan ketekalan keadaan.

以上がRedux とは何ですか? どのように使用できますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!