什么是 Redux,我们如何使用它?
什么是 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 /> // 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中文网其他相关文章!

热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

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

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

不同JavaScript引擎在解析和执行JavaScript代码时,效果会有所不同,因为每个引擎的实现原理和优化策略各有差异。1.词法分析:将源码转换为词法单元。2.语法分析:生成抽象语法树。3.优化和编译:通过JIT编译器生成机器码。4.执行:运行机器码。V8引擎通过即时编译和隐藏类优化,SpiderMonkey使用类型推断系统,导致在相同代码上的性能表现不同。

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

从C/C 转向JavaScript需要适应动态类型、垃圾回收和异步编程等特点。1)C/C 是静态类型语言,需手动管理内存,而JavaScript是动态类型,垃圾回收自动处理。2)C/C 需编译成机器码,JavaScript则为解释型语言。3)JavaScript引入闭包、原型链和Promise等概念,增强了灵活性和异步编程能力。

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。

Python和JavaScript在开发环境上的选择都很重要。1)Python的开发环境包括PyCharm、JupyterNotebook和Anaconda,适合数据科学和快速原型开发。2)JavaScript的开发环境包括Node.js、VSCode和Webpack,适用于前端和后端开发。根据项目需求选择合适的工具可以提高开发效率和项目成功率。
