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

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

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

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]删除
最新教程 更多>
  • MySQL动态更新列使用INNER JOIN方法
    MySQL动态更新列使用INNER JOIN方法
    MySQL动态更新关联表列数据 本文介绍如何在MySQL中使用INNER JOIN动态更新目标表中的列。 我们的目标是根据共享的名称属性,将源表(tableA)中对应列的值更新到目标表(tableB)中的列。 可以使用以下UPDATE语句实现: UPDATE tableB INNER JOIN ...
    编程 发布于2025-04-19
  • 如何使用Python理解有效地创建字典?
    如何使用Python理解有效地创建字典?
    在python中,词典综合提供了一种生成新词典的简洁方法。尽管它们与列表综合相似,但存在一些显着差异。与问题所暗示的不同,您无法为钥匙创建字典理解。您必须明确指定键和值。 For example:d = {n: n**2 for n in range(5)}This creates a dicti...
    编程 发布于2025-04-19
  • 为什么使用Firefox后退按钮时JavaScript执行停止?
    为什么使用Firefox后退按钮时JavaScript执行停止?
    导航历史记录问题:JavaScript使用Firefox Back Back 此行为是由浏览器缓存JavaScript资源引起的。要解决此问题并确保在后续页面访问中执行脚本,Firefox用户应设置一个空功能。 警报'); }; alert('inline Alert')...
    编程 发布于2025-04-19
  • Python中何时用"try"而非"if"检测变量值?
    Python中何时用"try"而非"if"检测变量值?
    使用“ try“ vs.” if”来测试python 在python中的变量值,在某些情况下,您可能需要在处理之前检查变量是否具有值。在使用“如果”或“ try”构建体之间决定。“ if” constructs result = function() 如果结果: 对于结果: ...
    编程 发布于2025-04-19
  • 如何在Chrome中居中选择框文本?
    如何在Chrome中居中选择框文本?
    选择框的文本对齐:局部chrome-inly-ly-ly-lyly solument 您可能希望将文本中心集中在选择框中,以获取优化的原因或提高可访问性。但是,在CSS中的选择元素中手动添加一个文本 - 对属性可能无法正常工作。初始尝试 state)</option> < op...
    编程 发布于2025-04-19
  • 您可以使用CSS在Chrome和Firefox中染色控制台输出吗?
    您可以使用CSS在Chrome和Firefox中染色控制台输出吗?
    在javascript console 中显示颜色是可以使用chrome的控制台显示彩色文本,例如红色的redors,for for for for错误消息?回答是的,可以使用CSS将颜色添加到Chrome和Firefox中的控制台显示的消息(版本31或更高版本)中。要实现这一目标,请使用以下模...
    编程 发布于2025-04-19
  • 如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    How to Resolve "General error: 2006 MySQL server has gone away" While Inserting RecordsIntroduction:Inserting data into a MySQL database can...
    编程 发布于2025-04-19
  • PHP如何在MySQL数据库中存储IP地址?
    PHP如何在MySQL数据库中存储IP地址?
    MySQL数据库IP地址使用PHP 使用PHP中存储IP地址时,使用PHP存储IP地址时,考虑到适当的字段类型和存储方法是至关重要的。 type 地址最合适的字段类型是int。尽管显然不匹配,但此选择还是由通过PHP IP2长函数从IP地址到整数的有效转换过程驱动的。要检索原始IP地址,可以使用...
    编程 发布于2025-04-19
  • 查找当前执行JavaScript的脚本元素方法
    查找当前执行JavaScript的脚本元素方法
    如何引用当前执行脚本的脚本元素在某些方案中理解问题在某些方案中,开发人员可能需要将其他脚本动态加载其他脚本。但是,如果Head Element尚未完全渲染,则使用document.getElementsbytagname('head')[0] .appendChild(v)的常规方...
    编程 发布于2025-04-19
  • 10款在线定制GIF制作工具推荐
    10款在线定制GIF制作工具推荐
    [2 在这篇文章中,我们收集了10种免费的在线GIF Maker工具,以制作您自己的自定义Ajax装载机 。易于创建自己的图像即可创建自己的自定义动画。 相关文章: 5在线加载ajax旋转器生成器工具 1。 gifmake.com 与(GIF,JPEG,PNG)构成图片,也可以分解动画gif。...
    编程 发布于2025-04-19
  • 如何使用PHP从XML文件中有效地检索属性值?
    如何使用PHP从XML文件中有效地检索属性值?
    从php $xml = simplexml_load_file($file); foreach ($xml->Var[0]->attributes() as $attributeName => $attributeValue) { echo $attributeName,...
    编程 发布于2025-04-19
  • 为什么HTML无法打印页码及解决方案
    为什么HTML无法打印页码及解决方案
    无法在html页面上打印页码? @page规则在@Media内部和外部都无济于事。 HTML:Customization:@page { margin: 10%; @top-center { font-family: sans-serif; font-weight: bo...
    编程 发布于2025-04-19
  • 如何有效地选择熊猫数据框中的列?
    如何有效地选择熊猫数据框中的列?
    在处理数据操作任务时,在Pandas DataFrames 中选择列时,选择特定列的必要条件是必要的。在Pandas中,选择列的各种选项。选项1:使用列名 如果已知列索引,请使用ILOC函数选择它们。请注意,python索引基于零。 df1 = df.iloc [:,0:2]#使用索引0和1 c...
    编程 发布于2025-04-19
  • 解决MySQL错误1153:数据包超出'max_allowed_packet'限制
    解决MySQL错误1153:数据包超出'max_allowed_packet'限制
    mysql错误1153:故障排除比“ max_allowed_pa​​cket” bytes 更大的数据包,用于面对阴谋mysql错误1153,同时导入数据capase doft a Database dust?让我们深入研究罪魁祸首并探索解决方案以纠正此问题。理解错误此错误表明在导入过程中接...
    编程 发布于2025-04-19
  • 在PHP中如何高效检测空数组?
    在PHP中如何高效检测空数组?
    在PHP 中检查一个空数组可以通过各种方法在PHP中确定一个空数组。如果需要验证任何数组元素的存在,则PHP的松散键入允许对数组本身进行直接评估:一种更严格的方法涉及使用count()函数: if(count(count($ playerList)=== 0){ //列表为空。 } 对...
    编程 发布于2025-04-19

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

Copyright© 2022 湘ICP备2022001581号-3