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;
相关推荐
前端不太难2 小时前
用 RN 的渲染模型,反推 Vue 列表的正确拆分方式
前端·javascript·vue.js
JS_GGbond2 小时前
防抖与节流:前端性能优化“双剑客”
前端
KLW752 小时前
vue v-if和v-show比较
前端·css·css3
梵尔纳多2 小时前
使用 Electron 实现一个简单的文本编辑器
前端·javascript·electron
晴殇i2 小时前
SPA首屏加载速度优化!
前端
qq. 28040339842 小时前
react 副作用探究
前端·react.js
小oo呆2 小时前
【自然语言处理与大模型】LangChainV1.0入门指南:核心组件Streaming
前端·javascript·easyui
Aotman_2 小时前
Vue.directive:自定义指令及传参
前端·javascript·vue.js·elementui·ecmascript·es6
wangchen_02 小时前
C++<fstream> 深度解析:文件 I/O 全指南
开发语言·前端·c++