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;
相关推荐
码艺-Alimjan10 分钟前
Tauri 网站To桌面应用实战总结
前端·javascript·vue
颜进强30 分钟前
18 · NestJS动态模块与 forRoot:`imports: [ConfigModule.forRoot({...})]` 到底在 import 什么
前端·后端·ai编程
YZ12255242 分钟前
【Docker专题】使用Docker部署Vue-Flask项目前后端分离版【前端Docker部署】
前端·vue.js·docker
liangshanbo121544 分钟前
浏览器渲染过程:高级前端面试题
前端
太子釢1 小时前
React 函数组件与 Hook 实践指南
前端·react.js
颜进强1 小时前
17 · 自定义 Provider 四形态:useValue / useClass / useFactory / useExisting 到底在选什么
前端·后端·ai编程
传人once1 小时前
网页文字滚动效果如何做
前端·css·html·jquery·html5
liangshanbo12151 小时前
面试题:React 中 Lane 和 Scheduler 是怎么配合的?
前端·react.js·前端框架
liangshanbo12151 小时前
请求拦截器相关面试题
java·前端·javascript
ShawnLiaoking1 小时前
ADS305 Big Data Lecuture4 Web Scraping
大数据·前端