”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 什么是 Redux,我们如何使用它?

什么是 Redux,我们如何使用它?

发布于2024-11-08
浏览:763

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]删除
最新教程 更多>
  • 如何在 PHP 中异步执行 cURL 请求?
    如何在 PHP 中异步执行 cURL 请求?
    PHP中的异步Curl请求在PHP中异步执行curl post请求可以提高性能并防止潜在的延迟。以下是如何使用不同的方法实现此目的:使用异步 cURL 函数使用curl_multi_*时,您可以同时执行多个 cURL 请求。下面是一个示例代码:$curl = curl_init($request);...
    编程 发布于2024-11-08
  • 如何将 Boehm 垃圾收集器与 C++ 标准库类(如“std::vector”和“std::string”)集成?
    如何将 Boehm 垃圾收集器与 C++ 标准库类(如“std::vector”和“std::string”)集成?
    将 Boehm 垃圾收集器与 C 标准库结合使用开发多线程 C 应用程序时,Boehm 保守的垃圾收集器对于简化内存非常有用管理。这就提出了如何将 Boehm GC 与 C 标准库的类(如 std::map 和 std::vector)集成的问题。一种方法涉及重新定义全局运算符 ::new 以使用 ...
    编程 发布于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:33...
    编程 发布于2024-11-08
  • 混淆技术真的可以保护可执行文件免受逆向工程的影响吗?
    混淆技术真的可以保护可执行文件免受逆向工程的影响吗?
    保护可执行文件免遭逆向工程:解决方案有限的挑战保护代码免遭未经授权的逆向工程是开发人员持续关注的问题,尤其是当它包含敏感信息。虽然已经提出了各种方法,但重要的是要承认完全防止逆向工程实际上是不可能的。常见混淆技术用户建议的策略,例如代码注入、混淆和自定义启动例程的目的是使反汇编变得不那么简单。然而,...
    编程 发布于2024-11-08
  • 掌握 Laravel 中的 Eloquent where 条件
    掌握 Laravel 中的 Eloquent where 条件
    Laravel 的 Eloquent ORM(对象关系映射)是其突出的功能之一,提供了一种与数据库交互的强大而富有表现力的方式。 Eloquent 提供的一项基本功能是方法,它允许开发人员高效、直观地过滤查询。在本文中,我们将深入研究 where 条件,探索其各种形式和实际用例。 ...
    编程 发布于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:添加 ArrayB...
    编程 发布于2024-11-08
  • 如何使用 CSS 在图像地图上实现鼠标悬停效果?
    如何使用 CSS 在图像地图上实现鼠标悬停效果?
    使用 CSS 设置图像地图鼠标悬停样式创建交互式网页时,通常需要包含具有可单击区域的图像。通常,这是使用图像映射来实现的。然而,事实证明,在鼠标悬停时设置这些区域的样式以提供额外的交互性是难以实现的。过去,尝试使用 CSS 设置这些区域的样式所取得的成功有限,如提供的示例所示:<img src...
    编程 发布于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

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3