当前位置: 首页 > news >正文

react 状态管理

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.mrgr.cn/news/38017.html

相关文章:

  • 【友元补充】【动态链接补充】
  • OpenMV与STM32通信全面指南
  • Python 封装 socket 为 [TCP/UDP/MULTICAST] 服务端
  • Python软体中使用TensorFlow实现一个简单的神经网络:从零开始
  • 大话 RCU (read copy update)
  • 保姆级复现yolov7(论文复现)
  • [数据集][目标检测]辣椒缺陷检测数据集VOC+YOLO格式695张5类别
  • 设计模式、系统设计 record part02
  • Java安全最佳实践:防御常见网络攻击
  • Study--Oracle-09--部署Openfiler存储服务器
  • 【机器学习】---深入探讨图神经网络(GNN)
  • 深信服2025届全球校招研发笔试-C卷(AK)
  • 一不小心,给腾讯云提了一个Bug
  • 学习ubuntu 24.10系统目录架构
  • uniapp view增加删除线
  • Python 统计学
  • 黑马头条day5- 延迟任务精准发布文章
  • 提升效率的秘密武器选择指南
  • 舒舒活动图片 小暑至,暑气湿气缠身怎么办?中医教你消暑宁心,健脾祛湿
  • 1.6 物理层