什么是 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 的核心组件是:
为了更好地理解 Redux 是什么以及它是如何工作的,让我们探索一下它的关键组件。本质上,Redux 由以下三个部分组成:
**1。商店
- 行动
- 减速器**
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></app> // Rendering the main App component </provider> )`
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?
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 会创建状态的新副本并进行必要的更改,而不是直接修改现有状态。
reducer更新状态后,变化就会反映出来。例如,将新商品添加到购物车后,更新的状态包括 noOfItemInCart 的递增值以及购物车数组中新添加的商品。这种结构化方法可确保可预测的状态更新并保持 Redux 应用程序中管理状态的一致性。
学习Redux及其重要性
Redux 遵循三个关键原则:
- 集中状态管理:整个应用程序状态存储在单个集中存储中,并以独特的树状结构组织。
- 操作驱动的状态更新:状态更改是通过分派操作发起的,这些操作是描述应用程序中发生的情况的对象。
- 通过Reducers进行状态转换:Reducers决定状态树如何对操作做出反应,确保可预测的更新并保持状态一致性。
以上是什么是 Redux,我们如何使用它?的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

本文讨论了在浏览器中优化JavaScript性能的策略,重点是减少执行时间并最大程度地减少对页面负载速度的影响。

本文讨论了使用浏览器开发人员工具的有效JavaScript调试,专注于设置断点,使用控制台和分析性能。

将矩阵电影特效带入你的网页!这是一个基于著名电影《黑客帝国》的酷炫jQuery插件。该插件模拟了电影中经典的绿色字符特效,只需选择一张图片,插件就会将其转换为充满数字字符的矩阵风格画面。快来试试吧,非常有趣! 工作原理 插件将图片加载到画布上,读取像素和颜色值: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data 插件巧妙地读取图片的矩形区域,并利用jQuery计算每个区域的平均颜色。然后,使用

本文将引导您使用jQuery库创建一个简单的图片轮播。我们将使用bxSlider库,它基于jQuery构建,并提供许多配置选项来设置轮播。 如今,图片轮播已成为网站必备功能——一图胜千言! 决定使用图片轮播后,下一个问题是如何创建它。首先,您需要收集高质量、高分辨率的图片。 接下来,您需要使用HTML和一些JavaScript代码来创建图片轮播。网络上有很多库可以帮助您以不同的方式创建轮播。我们将使用开源的bxSlider库。 bxSlider库支持响应式设计,因此使用此库构建的轮播可以适应任何

核心要点 利用 JavaScript 增强结构化标记可以显着提升网页内容的可访问性和可维护性,同时减小文件大小。 JavaScript 可有效地用于为 HTML 元素动态添加功能,例如使用 cite 属性自动在块引用中插入引用链接。 将 JavaScript 与结构化标记集成,可以创建动态用户界面,例如无需页面刷新的选项卡面板。 确保 JavaScript 增强功能不会妨碍网页的基本功能至关重要;即使禁用 JavaScript,页面也应保持功能正常。 可以使用高级 JavaScript 技术(

数据集对于构建API模型和各种业务流程至关重要。这就是为什么导入和导出CSV是经常需要的功能。在本教程中,您将学习如何在Angular中下载和导入CSV文件


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

WebStorm Mac版
好用的JavaScript开发工具

Dreamweaver Mac版
视觉化网页开发工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

记事本++7.3.1
好用且免费的代码编辑器