react 状态管理

news/2024/9/28 23:12:48 标签: react.js

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.niftyadmin.cn/n/5682038.html

相关文章

基于51单片机的2路电压采集proteus仿真

地址&#xff1a;https://pan.baidu.com/s/1oNOJJv78ecfWZkdlMyhNVQ 提取码&#xff1a;1234 仿真图&#xff1a; 芯片/模块的特点&#xff1a; AT89C52/AT89C51简介&#xff1a; AT89C52/AT89C51是一款经典的8位单片机&#xff0c;是意法半导体&#xff08;STMicroelectron…

EasyExcel全面实战:掌握多样化的Excel导出能力

1 概述 本文将通过实战案例全面介绍EasyExcel在Excel导出方面的多种功能。内容涵盖多表头写入、自定义格式、动态表头生成、单元格合并应用等。通过这些实例,读者可以掌握EasyExcel的各种高级功能,并在实际项目中灵活应用。 白日依山尽,黄河入海流。 欲穷千里目,更上一层楼…

秦巴山区SHP格式矢量范围

‌秦巴山区的shp范围包括河南、湖北、重庆、四川、陕西、甘肃六省市的80个县(市、区)。‌这一区域不仅地理范围广泛&#xff0c;而且生态多样性丰富&#xff0c;是国家重要的生物多样性和水源涵养生态功能区。秦巴山区的地貌类型以山地丘陵为主&#xff0c;间有汉中、安康、商丹…

【C++】继承,菱形继承,虚拟继承,组合详解

目录 1. 继承概念与定义 1.1 概念 1.2 定义 2. 父类与子类的赋值规则 3. 继承的作用域 4. 子类的默认成员函数 5. 继承与友元 6. 继承与静态成员 7. 菱形继承 7.1 继承关系 7.2 菱形继承的问题 7.3 虚拟继承 8. 继承与组合 1. 继承概念与定义 1.1 概念 1. 继承&a…

open-resty 服务安装redis插件

从github下载 作者&#xff1a;程序那点事儿 日期&#xff1a;2023/11/16 22:04 lua-resty-redis-cluster cd /usr/local/openresty/modules #进入到modules目录git clone https://github.com/cuiweixie/lua-resty-redis-cluster.git #下载插件mv lua-resty-redis-cluster/ …

使用 Spring Boot 和 EasyExcel 进行动态表头导出 Excel

引言 在企业级应用中&#xff0c;经常需要将数据导出为 Excel 文件&#xff0c;以便用户进行分析和查看。Spring Boot 结合 EasyExcel 可以非常方便地实现这一需求。本文将详细介绍如何使用 Spring Boot 和 EasyExcel 进行动态表头的 Excel 导出。 环境准备 1. 添加依赖 首…

【球形空间产生器】

题目 代码 #pragma GCC optimize(3) #include <bits/stdc.h> using namespace std; const double eps 1e-6; const int N 12; double g[N][N]; double ss[N]; int n; void gauss() {int c, r, t;for(c 1, r 1; c < n; c){int t r;for(int i r1; i < n; i)i…

Java---异常及处理

一.异常 1.概念 程序的非正常执行。高级语言都有异常处理机制&#xff08;C&#xff0c;Java&#xff09; 2.一般处理异常的方法 Scanner sc new Scanner(System.in);System.out.println("请输入一个数字:");String s sc.nextLine();if (s.matches("[0-9]&qu…