react --> redux

redux 在 react 中使用

redux 介绍

是一个专门用来做状态管理的js库(不是react插件)

可以用在vue、react、angular项目中,但基本与react配合使用

作用:集中式管理react应用中的多个组件共享的状态

redux-toolkit 和 react-redux

这两个库才是实际上在 react 中使用进行状态管理的库。

安装

npm install @reduxjs/toolkit react-redux

概念

概念 作用 对应 RTK 工具
Store 存储全局状态的容器(唯一数据源) configureStore(创建 Store)
Slice 拆分状态模块(如用户模块、购物车模块) createSlice(定义切片)
Reducer 纯函数,根据 Action 修改状态(不可直接改) Slice 内置 reducer 函数
Action 描述状态变化的 "指令"(如 "添加商品") Slice 自动生成 Action Creator
Dispatch 发送 Action 给 Reducer 的方法 useDispatch(组件中调用)
Selector 从 Store 中读取状态的方法 useSelector(组件中读取)

使用

  1. 创建 Slice(拆分状态模块)
  2. 创建 Store(存储全局状态的容器)
  3. 全局注入Store
  4. 在组件中使用
tsx 复制代码
// 创建Slice src/store/slice/auth/index.ts

import { createSlice,type Slice} from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';

export interface UserState {
  name: string;
  theme: 'light' | 'dark';
}

const initialState: UserState = {
  name:  '',
  theme: 'light',
};

export const authSlice: Slice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    setUser: (state, action: PayloadAction<{ name: string }>) => {
      state.name = action.payload.name;
    },
    setTheme: (state, action: PayloadAction<'light' | 'dark'>) => {
      state.theme = action.payload;
    },
  },
});

export const { setUser, setTheme } = authSlice.actions;
export default authSlice.reducer;

// 创建Store src/store/index.ts 汇总分片

import { configureStore } from '@reduxjs/toolkit';

import { authSlice } from './slice/auth';
import { articleSlice } from './slice/article';

const store = configureStore({
  reducer: {
    auth: authSlice.reducer,
    article: articleSlice.reducer,
  },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export default store;

// 全局注入Store src/main.tsx
import { createRoot } from "react-dom/client";
import { Provider } from "react-redux";
import App from "@/App";
import ErrorBoundary from "@/layouts/ErrorBoundary";

import store from "@/store";

function setupApp() {

  const container = document.getElementById("root");
  if (!container) return <>请绑定容器</>;
  const root = createRoot(container);
  root.render(
    <ErrorBoundary>
      <Provider store={store}>
        {/* 全局注入Store ,在所有的子组件中都可以使用 store*/}
        <App />
      </Provider>
    </ErrorBoundary>
  );
}

setupApp();

// 在组件中使用

import { useSelector, useDispatch } from "react-redux";
import type { RootState } from "../../store";
import { setUser ,type UserState} from "@/store/slice/auth";

function Home() {
  const auth: UserState = useSelector((state: RootState) => state.auth);
  const dispatch = useDispatch();
  return (
    <div className="f-c flex-col h-screen bg-bg-primary">

        <h2>Auth Slice</h2>
        <p>User Name: {auth.name}</p>
        <p>Theme: {auth.theme}</p>
        <button onClick={() => dispatch(setUser({ name: "Jim" }))}>Set User</button>
    </div>
  );
}

export default Home;
相关推荐
生戎马 平安京策15 分钟前
只学一点点:我的技术学习策略
前端·javascript·react.js
大鹏说大话29 分钟前
HTML5 地理定位 Geolocation:获取用户位置的“红线”与最佳实践
前端·html·html5
Csvn1 小时前
content-visibility: auto —— 让浏览器跳过离屏渲染的性能黑科技
前端
小鹰信息技术服务部1 小时前
Edge安装包MicrosoftEdgeSetup.exe无法运行,点击没反应
前端·edge
webkubor2 小时前
一次前端生产白屏复盘:旧 HTML、Hash 资源和 MIME type text/html
前端·前端工程化
咩咩啃树皮2 小时前
第63篇【终极整合巨作】从零手写原生中后台管理系统|整合62篇全部前端知识点|从头到尾完整架构+全功能逻辑
前端·架构
Highcharts3 小时前
用Highcharts如何动态向一个序列添加点-示列讲解
前端
weixin_431600443 小时前
做 Agent 会用到的 Node API(4):取消与 AbortController
前端·学习·ai·agent·ai编程
JiaLin_Denny3 小时前
Vue3中ref和reactive用法与双向数据绑定
前端·javascript·vue.js
用户2181697049303 小时前
Flutter(十)Container Center Align
前端