react 状态管理

news/2024/10/3 15:43:12/

Redux

ReduxReact中常用的状态管理组件,类似于Vue中的Pinia(Vuex),可以独立于框架运行

作用: 通过集中管理的方式管理应用的状态

配套工具

react中使用redux,官方要求按照两个插件,Redux Toolkitreact-redux

Redux Toolkit 是官方推荐编写Redux逻辑的方式,是一套工具的集合集,简化书写方式

react-redux 用来连接reduxreact组件的中间件

npm i @reduxjs/toolkit react-redux

store目录结构设计

  • 通常集中状态管理的部分都会单独创建一个store目录
  • 应用通常会有多个子store模块,所以创建一个modules目录,在内部编写业务分类的子store
  • store中的入口文件index.js的作用是组合modules中所有的子模块,并导出store

在这里插入图片描述

使用

counterStore.js

import { createSlice } from "@reduxjs/toolkit";const counterStore = createSlice({// 名称name: "counter",// 初始化状态initialState:{count:0},//修改数据的同步方法reducers:{add(store){store.count++},sub(store){store.count--}}
})
// 结构出action对象中的函数
const {add,sub} = counterStore.actions
// reducer函数
const currentReducer = counterStore.reducer
// 导出
export default currentReducer
export {add,sub}

index.js

import { configureStore } from "@reduxjs/toolkit";import counterReducer from "./modules/counterStore";// 创建根store组合子模块
const store = configureStore({reducer:{counter:counterReducer}
})export default store;

为react注入store
react-redux负责把ReduxReact连接起来,内置Provider组件,通过store参数把创建好的store实例注入到应用中。

main.jsx 项目的入口文件

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
import './index.css'
import store from './store'
import { Provider } from 'react-redux'createRoot(document.getElementById('root')).render(<StrictMode><Provider store={store}><App /></Provider></StrictMode>,
)

在组件中使用

react组件中使用store中的数据,需要用到一个钩子函数useSelector,它的作用是把store中的数据映射到组件中

function App() {const counterReducer = useSelector(state => state.counter);return (<div><div>当前值:{counterReducer.count}</div></div>);
}

在这里插入图片描述
在这里插入图片描述
React组件中修改store中的数据需要借助另外一个hook函数——useDispatch,它的作用是生成提交action对象的dispatch函数

import './App.css'
import { useSelector,useDispatch } from 'react-redux';// 导入创建的action对象的方法
import { add, sub } from './store/modules/counterStore';
function App() {const counterReducer = useSelector(state => state.counter);// 获取dispatch函数const dispatch = useDispatch();return (<div><div>当前值:{counterReducer.count}</div>{/* 调用 */}<button onClick={() => dispatch(add())}>加一</button><button onClick={() => dispatch(sub())}>减一</button></div>);
}

在这里插入图片描述

提交action传参

reducers的同步修改方法中添加action对象参数,在调用ationCreater的时候传递参数,参数会被传递到action对象的payload属性上

import { createSlice } from "@reduxjs/toolkit";const counterStore = createSlice({// 名称name: "counter",// 初始化状态initialState:{count:0},//修改数据的同步方法reducers:{add(store){store.count++},sub(store){store.count--},addNum(store,action){store.count+= action.payload}}
})
// 结构出action对象中的函数
const {add,sub,addNum} = counterStore.actions
// reducer函数
const currentReducer = counterStore.reducer
// 导出
export default currentReducer
export {add,sub,addNum}
在这里插入代码片
import './App.css'
import { useSelector,useDispatch } from 'react-redux';// 导入创建的action对象的方法
import { add, sub,addNum } from './store/modules/counterStore';
function App() {const counterReducer = useSelector(state => state.counter);// 获取dispatch函数const dispatch = useDispatch();return (<div><div>当前值:{counterReducer.count}</div>{/* 调用 */}<button onClick={() => dispatch(add())}>加一</button><button onClick={() => dispatch(sub())}>减一</button>{/* 加三 */}<button onClick={() => dispatch(addNum(3))}>加三</button></div>);
}

在这里插入图片描述

异步操作

  • 创建store的方式不变,配置好同步修改状态的方法
  • 单独封装一个函数,在函数内部return一个新函数,在新函数中
    • 封装异步请求获取数据
    • 调用同步actionCreate传入异步数据生成的一个action对象,并使用dispatch提交
  • 组件中dispatch的写法不变

englishStore.js

import { createSlice } from "@reduxjs/toolkit";
const englishStore = createSlice({name: "englishstore",// 初始化状态initialState: {// 英文内容content: "",// 中文内容note: "",},// 修改内容reducers: {changeEnglish(store, action) {console.log(action.payload);store.content = action.payload.content;store.note = action.payload.note;},},
});// 结构出action对象中的方法
const { changeEnglish } = englishStore.actions;// 异步请求
const fetchEnglish = () => {return async (dispatch) => {const res = await fetch("https://api.oioweb.cn/api/common/OneDayEnglish");const data = await res.json();console.log(data);// 修改状态dispatch(changeEnglish(data.result));};
};// reducer函数
const englishReducer = englishStore.reducer;// 导出
export default englishReducer;
export { fetchEnglish };

使用


import { useEffect } from 'react';
import './App.css'
import { useSelector, useDispatch } from 'react-redux';
import { fetchEnglish } from './store/modules/englishStore';function App() {const englishReducer = useSelector(state => state.english)const dispatch = useDispatch()useEffect(() => {// 触发异步请求dispatch(fetchEnglish())}, [dispatch])return (<div><div>中文:{englishReducer.note}</div><div>英文:{englishReducer.content}</div></div>);
}export default App

在这里插入图片描述


http://www.ppmy.cn/news/1533983.html

相关文章

some 蓝桥杯题

12.反异或01串 - 蓝桥云课 (lanqiao.cn) #include "bits/stdc.h" #define int long long using namespace std; char c[10000000]; char s[10000000]; int cnt,Ans,mr,mid; int maxi; int p[10000000],pre[10000000]; signed main() {ios::sync_with_stdio(0);cin.t…

Python 封装 socket 为 [TCP/UDP/MULTICAST] 客户端

发送 TCP/UDP/MULTICAST 数据并接收响应。 #!/usr/bin/env python # -*- coding: utf-8 -*- import socketclass ClientSocket:def __init__(self, *, protocol: str, ip: str, port: int, recv_timeout: float 1.5):"""客户端套接字发送 TCP/UDP/MULTICAST 数…

【嵌入式裸机开发】智能家居入门3(MQTT服务器、MQTT协议、微信小程序、STM32)

前面已经写了两篇博客关于智能家居的&#xff0c;服务器全都是使用ONENET中国移动&#xff0c;他最大的优点就是作为数据收发的中转站是免费的。本篇使用专门适配MQTT协议的MQTT服务器&#xff0c;有公用的&#xff0c;也可以自己搭建 前言一、项目总览二、总体流程分析1、了解…

python 实现md5算法

md5算法介绍 MD5&#xff08;Message-Digest Algorithm 5&#xff09;是一种广泛使用的加密散列函数&#xff0c;由Ronald Rivest于1991年设计&#xff0c;并在1992年正式发布。MD5可以将任意长度的“消息”&#xff08;也可以是文件&#xff09;计算出一个固定长度的“摘要”…

RabbitMQ 延迟消息

基本概念&#xff1a; 生产者发送消息时指定一个时间&#xff0c;消费者不会立刻收到消息&#xff0c;而是在指定时间之后才收到消息。 死信&#xff1a; 指那些无法被正常路由到队列的消息&#xff0c;或者在队列中无法被消费者正常消费的消息。当消息满足某些特定条件时&am…

音视频入门基础:FLV专题(7)——Tag header简介

一、引言 从《音视频入门基础&#xff1a;FLV专题&#xff08;3&#xff09;——FLV header简介》中可以知道&#xff0c; 在FLV header之后&#xff0c;FLV文件剩下的部分应由PreviousTagSize和Tag组成。FLV文件 FLV header PreviousTagSize0 Tag1 PreviousTagSize1 Ta…

SAP_FI_主数据和业务数据

在SAP的FI&#xff08;Financial Accounting&#xff09;模块中&#xff0c;主数据和业务数据是两个关键的组成部分。它们各自有着不同的定义和用途&#xff1a; 主数据 (Master Data) 主数据是指系统中较为静态且相对长期使用的数据&#xff0c;通常能够跨多个财务周期使用。…

相机、镜头参数详解以及相关计算公式

一、工业相机参数 1、分辨率 相机每次采集图像的像素点数&#xff0c;也是指这个相机总共有多少个感光晶片。在采集图像时&#xff0c;相机的分辨率对检测精度有很大的影响&#xff0c;在对同样打的视场成像时&#xff0c;分辨率越高&#xff0c;对细节的展示越明显。 相机像素…