首页  >  文章  >  web前端  >  Redux 指南:用于 JavaScript 应用程序的强大状态管理库

Redux 指南:用于 JavaScript 应用程序的强大状态管理库

王林
王林原创
2024-07-21 09:34:291089浏览

Guide to Redux: A Robust State Management Library for JavaScript Applications

Redux 被广泛认为是专为 JavaScript 应用程序设计的强大状态管理库,通常与流行的框架 React 一起使用。通过提供可靠的状态容器,Redux 建立了坚实的基础,大大简化了应用程序状态的处理和故障排除任务。本指南深入研究了构成 Redux 的基本组件,提供了每个元素的详细解释,并说明了它们如何协同互操作以简化应用程序的整体功能。这次深入的探索旨在阐明 Redux 的内部工作原理,使开发人员能够掌握这个状态管理工具的复杂性,并在他们的项目中有效地利用其功能。

目录

  1. Redux 简介
  2. 在 React 应用程序中设置 Redux
  3. 动作和动作类型
  4. Reducer 和 Slice
  5. 配置商店
  6. 连接 React 组件
  7. 结论和参考文献

1.Redux简介

Redux 遵循单向数据流模型,并基于三个核心原则:

  • 单一事实来源:整个应用程序的状态存储在单个存储中的对象树中。这种集中化使得调试和跟踪应用程序中的更改变得更加容易。
  • 状态是只读的:改变状态的唯一方法是发出一个动作,一个描述发生了什么的对象。这确保了状态突变是可预测和可追踪的。
  • 使用纯函数进行更改:要指定状态树如何通过操作进行转换,您可以编写纯减速器。纯函数是可预测和可测试的,这简化了调试和单元测试。

2. 在 React 应用程序中设置 Redux

首先,安装 Redux 和 React-Redux:

npm install redux react-redux @reduxjs/toolkit

此命令安装核心 Redux 库、Redux 的 React 绑定以及 Redux Toolkit,这简化了许多常见任务,例如设置存储和创建切片。

3. 动作和动作类型

操作是将数据从应用程序发送到 Redux 存储的信息负载。动作类型是表示动作的常量。

动作类型.js

export const INCREMENT = "INCREMENT";
export const DECREMENT = "DECREMENT";
export const INCREMENT_BY_VALUE = "INCREMENT_BY_VALUE";
export const RESET = "RESET";

export const increment = () => ({ type: INCREMENT });
export const decrement = () => ({ type: DECREMENT });
export const incrementByValue = (value) => ({
  type: INCREMENT_BY_VALUE,
  payload: value,
});
export const reset = () => ({ type: RESET });

定义操作和操作类型显然有助于保持一致性并减少应用程序中的错误。

4. 减速器和切片

Reducer 指定应用程序的状态如何更改以响应发送到存储的操作。切片是应用程序单个功能的 Redux 减速器逻辑和操作的集合,使用 Redux Toolkit 的 createSlice 方法创建。

counterSlice.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = { number: 0 };

const counterSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    increment: (state) => {
      state.number += 5;
    },
    decrement: (state) => {
      state.number = Math.max(0, state.number - 5);
    },
    incrementByValue: (state, action) => {
      state.number += action.payload;
    },
    reset: (state) => {
      state.number = 0;
    },
  },
});

export const { increment, decrement, incrementByValue, reset } = counterSlice.actions;

export default counterSlice.reducer;

要合并多个切片:

rootReducer.js

import { combineReducers } from "@reduxjs/toolkit";
import counterReducer from "../slices/counterSlice";

const rootReducer = combineReducers({
  counter: counterReducer,
});

export default rootReducer;

5. 配置商店

store是将actions和reducers结合在一起的对象。它保存应用程序状态,允许通过 getState() 访问它,通过dispatch(action) 更新它,并通过 subscribe(listener) 注册监听器。

商店.js

import { configureStore } from "@reduxjs/toolkit";
import rootReducer from "../reducers/rootReducer";

const store = configureStore({
  reducer: rootReducer,
});

export default store;

6. 连接 React 组件

要将 React 组件连接到 Redux 存储,请使用 react-redux 中的 Provider 组件将存储传递给您的组件,并使用 useSelector 和 useDispatch 钩子来访问和操作状态。

应用程序.js

import React from "react";
import { Provider } from "react-redux";
import store from "./redux/store/store";
import Counter from "./components/Counter";
import MusCo from "./MusCo redux Redux 指南:用于 JavaScript 应用程序的强大状态管理库.png";

function App() {
  return (
    <provider store="{store}">
      <div classname="container mx-auto mt-24 text-center">
        <img src="%7BMusCo%7D" alt="Redux 指南:用于 JavaScript 应用程序的强大状态管理库" classname="w-40 mx-auto mt-24 rounded-full">
        <h1 classname="container m-auto text-2xl font-semibold text-center text-violet-700">
          Practice Redux with <span classname="font-extrabold text-violet-900">MusCo</span>
        </h1>
        <div classname="relative inline-block mt-8 text-sm">
          <counter></counter>
          <h5 classname="absolute bottom-0 right-0 mb-2 mr-2 font-semibold text-violet-700">
            <span classname="italic font-normal">by</span> 
            <span classname="font-semibold text-violet-900">Mus</span>tafa 
            <span classname="font-semibold text-violet-900">Coskuncelebi</span>
          </h5>
        </div>
      </div>
    </provider>
  );
}

export default App;

CounterComponent.js

import { useDispatch, useSelector } from "react-redux";
import {
  decrement,
  increment,
  incrementByValue,
  reset,
} from "../slices/counterSlice";
import { useState, useEffect } from "react";

function Counter() {
  const [value, setValue] = useState("");
  const dispatch = useDispatch();
  const number = useSelector((state) => state.counter.number);

  useEffect(() => {
    const showcase = document.querySelector("#showcase");
    if (number 
      <h1 classname="mb-3 text-3xl font-bold mt-7 text-violet-700">Counter</h1>
      <p classname="text-5xl text-violet-900">{number}</p>
      <div classname="flex mx-8 space-x-5" style="{{" justifycontent:>
        <button onclick="{()"> dispatch(increment())} className="w-40 h-10 p-2 mt-5 rounded-md outline-1 outline-violet-500 outline text-violet-900" style={{ backgroundColor: "#c2ff72" }}>
          Increment by 5
        </button>
        <button onclick="{()"> dispatch(decrement())} className="w-40 h-10 p-2 mt-5 rounded-md outline-1 outline-violet-500 outline text-violet-900" style={number 
          Decrement by 5
        </button>
      </div>
      <div classname="flex mx-8 mt-5 space-x-3 mb-7" style="{{" justifycontent: alignitems:>
        <div classname="p-5 space-x-5 rounded-md outline outline-1 outline-violet-500">
          <input classname="w-40 h-10 pl-2 rounded-md outline outline-1 outline-violet-500 text-violet-900" onchange="{(e)"> {
                   let newValue = e.target.value.trim();
                   if (newValue === "") {
                     newValue = "";
                     reset();
                   }
                   if (/^\d*$/.test(newValue)) {
                     setValue(newValue);
                   }
                 }} 
                 value={value} 
                 placeholder="Enter Value" />
          <button onclick="{()"> {
            dispatch(incrementByValue(Number(value)));
            setValue("");
          }} className="w-40 h-10 p-2 rounded-md outline-1 outline-violet-500 outline text-violet-900" style={{ backgroundColor: "#c2ff72" }}>
            Add this Value
          </button>
        </div>
      </div>
      <button onclick="{()"> {
        dispatch(reset());
        setValue("");
      }} className="w-20 h-10 p-2 text-white rounded-md outline-1 outline-violet-500

 outline mb-7 bg-violet-900">
        Reset
      </button>
      <h3 classname="text-violet-400" id="showcase" style="{{" visibility: marginbottom:>
        Counter cannot be less than 0
      </h3>
    
  );
}

export default Counter;

7 结论和参考文献

Redux 是一个强大的库,用于管理应用程序中的状态。通过了解操作、减速器、存储以及如何将所有内容连接到 React 组件,您可以创建可预测和可维护的应用程序。

要点:

  • 操作:定义应用程序中应该发生的事情。
  • Reducers:指定状态如何响应操作而变化。
  • Store:保存状态并处理操作。
  • Provider:将 store 传递给你的 React 组件。

更多信息,请查看 Redux 官方文档:

  • Redux 文档
  • Redux 工具包文档
  • React-Redux 文档

通过遵循本指南,您应该对 Redux 有深入的了解,并能够在自己的应用程序中实现它。

以上是Redux 指南:用于 JavaScript 应用程序的强大状态管理库的详细内容。更多信息请关注PHP中文网其他相关文章!

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