首页  >  文章  >  web前端  >  什么是 Redux,我们如何使用它?

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

WBOY
WBOY原创
2024-08-29 11:03:34896浏览

什么是 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 的核心组件是:

What is Redux, and how can we use it?

为了更好地理解 Redux 是什么以及它是如何工作的,让我们探索一下它的关键组件。本质上,Redux 由以下三个部分组成:

**1。商店

  1. 行动
  2. 减速器**

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>
)`

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.

state参数有一个默认值initialCartState,这样reducer就可以处理第一次调用时状态未定义的场景。每个减速器必须处理默认状态,如果没有操作类型匹配,则返回当前状态。这确保了在调度不相关的操作时状态保持不变。

当一个action被调度时,根据action类型调用适当的reducer。在我们的示例中,当单击“添加到购物车”按钮时,操作创建者 addItemToCart 会调度 ADD_ITEM_TO_CART 类型的操作。

然后,cartReducer 通过匹配其类型来处理此操作。如果它与 ADD_ITEM_TO_CART 匹配,则会通过增加 noOfItemInCart 值并相应地将新商品添加到购物车数组来更新状态。

需要注意的是,Redux 强制执行不变性,因此,reducer 会创建状态的新副本并进行必要的更改,而不是直接修改现有状态。

reducer更新状态后,变化就会反映出来。例如,将新商品添加到购物车后,更新的状态包括 noOfItemInCart 的递增值以及购物车数组中新添加的商品。这种结构化方法可确保可预测的状态更新并保持 Redux 应用程序中管理状态的一致性。

What is Redux, and how can we use it?

学习Redux及其重要性

Redux 遵循三个关键原则:

  1. 集中状态管理:整个应用程序状态存储在单个集中存储中,并以独特的树状结构组织。
  2. 操作驱动的状态更新:状态更改是通过分派操作发起的,这些操作是描述应用程序中发生的情况的对象。
  3. 通过Reducers进行状态转换:Reducers决定状态树如何对操作做出反应,确保可预测的更新并保持状态一致性。

以上是什么是 Redux,我们如何使用它?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn