react 10之状态管理工具2 redux + react-redux +redux-saga

news2024/9/21 14:31:24

目录

  • react 10之状态管理工具2 redux +
    • store / index.js 入口文件
    • actionType.js actions常量的文件
    • rootReducer.js 总的reducer 用于聚合所有模块的 reducer
    • rootSaga.js 总的saga 用于聚合所有模块的 saga
    • store / form / formActions.js 同步修改 isShow
    • store / form / formReducer.js 同步修改 isShow
    • store / list / listActions.js 同步与异步修改 count、arr
    • store / list / listReducer.js 同步与异步修改 count、arr
    • store / list / listSaga.js 同步与异步修改 count、arr ( 获取最新的count和arr )
    • store / test / testActions.js 被add的异步修改了数据
    • store / test / testReducer.js 被add的异步修改了数据
    • index.js 项目入口文件引入
    • 7redux/3使用saga/app.jsx
    • 效果

react 10之状态管理工具2 redux +

  • npm install redux react-redux

  • npm i redux-saga

  • redux-saga

    • redux-saga是一个Redux的中间件,它允许你在Redux中编写异步的action creators。

store / index.js 入口文件

import { applyMiddleware, legacy_createStore } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from "./rootReducer";
import rootSaga from "./rootSaga";

const sagaMiddleware = createSagaMiddleware();

const store = legacy_createStore(rootReducer, applyMiddleware(sagaMiddleware));

sagaMiddleware.run(rootSaga);

export default store;

actionType.js actions常量的文件

// actionType.js 常量 唯一标识 标记当前action的唯一性
export const FORM_ADD_COUNT = 'form_addCount'
export const FORM_SUB_COUNT = 'form_subCount'
export const LIST_CHANGE_IsSHOW = 'list_change_isShow'

export const TEST_CHANGE_ARR = 'test_change_arr'

rootReducer.js 总的reducer 用于聚合所有模块的 reducer

// rootReducer.js 总的reducer 用于聚合所有模块的 reducer
import { combineReducers } from 'redux';
import formReducer from './form/formReducer';
import listReducer from './list/listReducer';
import testReducer from './test/testReducer';

const rootReducer = combineReducers({
  list: listReducer,
  form: formReducer,
  test: testReducer
});

export default rootReducer;

rootSaga.js 总的saga 用于聚合所有模块的 saga

// rootSaga.js 总的saga 用于聚合所有模块的 saga
import { all } from 'redux-saga/effects';
import watchListActions from './list/listSaga';

function* rootSaga() {
  yield all([
    watchListActions()
  ]);
}

export default rootSaga;

store / form / formActions.js 同步修改 isShow

// formActions.js
import { LIST_CHANGE_IsSHOW } from "../actionType";
export const list_changeShow = () => ({
  type: LIST_CHANGE_IsSHOW,
});

store / form / formReducer.js 同步修改 isShow

// formReducer.js
import { LIST_CHANGE_IsSHOW } from "../actionType";
const initialState = {
  isShow: false
};

const formReducer = (state = initialState, action) => {
  switch (action.type) {
    case LIST_CHANGE_IsSHOW:
      return { ...state, isShow: !state.isShow };
    default:
      return state;
  }
};

export default formReducer;

store / list / listActions.js 同步与异步修改 count、arr

// listActions.js
import { FORM_ADD_COUNT, FORM_SUB_COUNT } from "../actionType";
export const form_addCount = () => ({
  type: FORM_ADD_COUNT
});

export const form_subCount = () => ({
  type: FORM_SUB_COUNT
});

store / list / listReducer.js 同步与异步修改 count、arr

// listReducer.js
import { FORM_ADD_COUNT, FORM_SUB_COUNT } from "../actionType";
const initialState = {
  count: 0
};

const listReducer = (state = initialState, action) => {
  switch (action.type) {
    case FORM_ADD_COUNT:
      return { ...state, count: state.count + 1 };
    case FORM_SUB_COUNT:
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
};

export default listReducer;

store / list / listSaga.js 同步与异步修改 count、arr ( 获取最新的count和arr )

// listSaga.js
import { delay, put, select, takeEvery } from 'redux-saga/effects';
import { FORM_ADD_COUNT, FORM_SUB_COUNT, TEST_CHANGE_ARR } from "../actionType";

function* form_addCountAsync() {
  // 异步操作,例如发送网络请求等
  yield console.log('add count...',)
  // const currentCount = yield select((state) => state.list.count);
  // console.log('currentCount',currentCount); // 获取到count最新的值 可以用于发起异步请求啥的
  yield delay(2000); // 延迟2s后 再触发 TEST_CHANGE_ARR
  let currentArrLength = yield select((state) => state.test.arr)
  currentArrLength = currentArrLength?.length  + 1
  console.log('currentArrLength',currentArrLength);
  yield put({ type: TEST_CHANGE_ARR ,payload:'我是-' + currentArrLength}); // 修改test模块的 arr数据
}

function* form_subCountAsync() {
  // 异步操作,例如发送网络请求等
  yield console.log('sub count...');
}

function* watchListActions() {
  yield takeEvery(FORM_ADD_COUNT, form_addCountAsync);
  yield takeEvery(FORM_SUB_COUNT, form_subCountAsync);
}

export default watchListActions;

store / test / testActions.js 被add的异步修改了数据

// testActions.js
import { TEST_CHANGE_ARR } from "../actionType";
export const test_change_arr = () => ({
  type: TEST_CHANGE_ARR,
});

store / test / testReducer.js 被add的异步修改了数据

// testReducer.js
import { TEST_CHANGE_ARR } from "../actionType";
const initialState = {
  arr: []
};

const testReducer = (state = initialState, action) => {
  console.log('action',action);
  switch (action.type) {
    case TEST_CHANGE_ARR:
      return { ...state, arr: [...state.arr,action.payload] };
    default:
      return state;
  }
};

export default testReducer;

index.js 项目入口文件引入

import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import App from "./7redux/3使用saga/app";
import store from "./store/index.js";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <Provider store={store}>
        <App />
    </Provider>
);

7redux/3使用saga/app.jsx

import React from 'react';
import { connect } from 'react-redux';
import { list_changeShow } from '../../store/form/formActions';
import { form_addCount, form_subCount } from '../../store/list/listActions';

class App extends React.Component {
  render() {
    // console.log('this.props',this.props);
    const { count, isShow, form_subCount, form_addCount, list_changeShow,arr } = this.props;

    return (
      <div>
        <p>Count: {count}</p>
        <button onClick={form_addCount}>addcount</button>
        <button onClick={form_subCount}>Decrement</button>

        <p>isShow: {isShow ? 'True' : 'False'}</p>
        <button onClick={list_changeShow}>Toggle Show</button>

        <p>arr: {arr}</p>
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  count: state.list.count,
  isShow: state.form.isShow,
  arr: state.test.arr,
});

const mapDispatchToProps = {
  form_addCount,
  form_subCount,
  list_changeShow
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

效果

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/902339.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

[机缘参悟-100] :今早的感悟:儒释道代表了不同的人生观、思维模式决定了人的行为模式、创业到处是陷阱、梦想与欺骗其实很容易辨认

目录 一、关于儒释道 二、关于成长性思维与固定性思维 三、关于创业 四、关于梦想与忽悠 一、关于儒释道 儒&#xff1a;逆势而为&#xff0c;修身齐家治国平天下&#xff0c;大公无私 佛&#xff1a;万法皆空&#xff0c;众生皆苦&#xff0c;普度众生&#xff0c;无公无…

如何构建 NodeJS 影院微服务并使用 docker 进行部署

图片来自谷歌 — 封面由我制作 一、说明 构建一个微服务的电影网站&#xff0c;需要Docker、NodeJS、MongoDB&#xff0c;这样的案例您见过吗&#xff1f;如果对此有兴趣&#xff0c;您就继续往下看吧。 在本系列中&#xff0c;我们将构建一个 NodeJS 微服务&#xff0c;并使用…

相邻节点迭代器(Java 实例代码源码包下载)

目录 相邻节点迭代器 Java 实例代码 src/runoob/graph/DenseGraphIterater.java 文件代码&#xff1a; src/runoob/graph/SparseGraphIterater.java 文件代码&#xff1a; 相邻节点迭代器 图论中最常见的操作就是遍历邻边&#xff0c;通过一个顶点遍历相关的邻边。邻接矩阵…

Python编程基础-函数

函数定义与调用 将完成某一特定功能并经常使用的代码编写成函数&#xff0c;在需要使用时直接调用 def 函数名(函数参数): 函数体 return 表达式或者值 def printHello(): #打印hello字符串print (hello)def printNum(): #输出0--9数字for i in range(0,10):print (i)return…

Unity 变量修饰符 之protected ,internal,const , readonly, static

文章目录 protectedinternalconstreadonlystatic protected 当在Unity中使用C#编程时&#xff0c;protected是一种访问修饰符&#xff0c;用于控制类成员&#xff08;字段、方法、属性等&#xff09;的可见性和访问权限。protected修饰的成员可以在当前类内部、派生类&#xf…

大数据背景和概念

一、背景 1.岗位现状 大数据在一线互联网已经爆发了好多年&#xff0c;2015年-2020年&#xff08;国内互联网爆发期&#xff09;那时候的大数据开发&#xff0c;刚毕业能写Hive SQL配置个离线任务、整个帆软报表都20K起步。如果做到架构师&#xff0c;50K跑不掉。现在市场回归…

字符串旋转(2)

题目要求&#xff1a; 写一个函数&#xff0c;判断一个字符串是否为另外一个字符串旋转之后的字符串。 例如&#xff1a; 给定s1 AABCD和s2 BCDAA&#xff0c;返回1。给定s1abcd和s2ACBD&#xff0c;返回0。AABCD左旋一个字符得到ABCDAAABCD左旋两个字符得到BCDAAAABCD右旋一个…

Stm32学习记录之中断

1、前言 该系列文章用于记录个人学习stm32单片机的过程&#xff0c;欢迎指导讨论~。 2、中断知识点梳理 中断 { N V I C ( 内嵌向量中断控制器 ) { 中断向量表 优先级 { 抢占优先级 响应优先级 自然优先级 优先级分组 E X T I ( 外部中断 ) { 触发方式 { 上边沿 下边沿 双边沿 …

wazuh安装、Rootkit原理解析与检测实践

目录 1.wazuh 1&#xff09;什么是wazuh 2&#xff09;安装wazuh 方法一&#xff1a;仓库安装&#xff08;跟着官方文档走&#xff09; 方法二&#xff1a;虚拟机OVA安装 2.Rootkit原理解析与检测实践 Rootkit主要分为以下2种 解压并编译这个文件 利用chkrootkit检查rootk…

看了这么多热闹,AI帮助你解决实际问题了吗?

经历了近两个月的日更之后&#xff0c;这个星期发文频率有所下降&#xff0c;日更需要花费更多的时间精力&#xff0c;而这恰恰是一个人忙起来之后无法保证的。后续发文频率稍做调整&#xff0c;内容会继续保持更新。 前几日小米发布会&#xff08;雷老板2023年度演讲&#xff…

EndNote-文献管理工具【安装篇】

下载&#xff1a;&#xff08;文末附安装包&#xff0c;建议使用这一个&#xff0c;官网都需要付费&#xff09; 打开安装包&#xff0c;双击&#xff1a; 安装完了之后不要直接运行&#xff0c;因为EndNote软件少了一个类型的软件&#xff1a;GB/T17714。 因此我们需要把这个…

实现两个栈模拟队列

实现两个栈模拟队列 思路&#xff1a;可以想象一下左手和右手&#xff0c;两个栈&#xff1a;stack1&#xff08;数据所在的栈&#xff09; &#xff0c;stack2&#xff08;临时存放&#xff09;。 入队&#xff1a;需要将入队 num 加在 stack1 的栈顶即可&#xff1b; 出队&am…

plt绘制箱型图+散点图

import numpy as np import matplotlib.pyplot as plt# 创建示例数据 np.random.seed(1) data [np.random.normal(0, std, 100) for std in range(1, 4)]# 绘制箱型图 plt.boxplot(data, patch_artistTrue,zorder0)# 添加数据点的散点图&#xff0c;并设置参数以避免重叠 for …

[四次挥手]TCP四次挥手握手由入门到精通(知识精讲)

⬜⬜⬜ &#x1f430;&#x1f7e7;&#x1f7e8;&#x1f7e9;&#x1f7e6;&#x1f7ea;(*^▽^*)欢迎光临 &#x1f7e7;&#x1f7e8;&#x1f7e9;&#x1f7e6;&#x1f7ea;&#x1f430;⬜⬜⬜ ✏️write in front✏️ &#x1f4dd;个人主页&#xff1a;陈丹宇jmu &am…

Pytorch的torch.utils.data中Dataset以及DataLoader等详解

在我们进行深度学习的过程中&#xff0c;不免要用到数据集&#xff0c;那么数据集是如何加载到我们的模型中进行训练的呢&#xff1f;以往我们大多数初学者肯定都是拿网上的代码直接用&#xff0c;但是它底层的原理到底是什么还是不太清楚。所以今天就从内置的Dataset函数和自定…

【Go】Go 文本匹配 - 正则表达式基础与编程中的应用 (8000+字)

正则表达式&#xff08;Regular Expression, 缩写常用regex, regexp表示&#xff09;是计算机科学中的一个概念&#xff0c;很多高级语言都支持正则表达式。 目录 何为正则表达式 语法规则 普通字符 字符转义 限定符 定位符 分组构造 模式匹配 regexp包 MatchString…

websocker无法注入依赖

在公司中准备用websocker统计在线人数&#xff0c;在WebSocketServer使用StringRedisTemplate保存数据到redis中去&#xff0c;但是在保存的时候显示 StringRedisTemplate变量为null 详细问题 2023-08-20 10:37:14.109 ERROR 28240 --- [nio-7125-exec-1] o.a.t.websocket.po…

【AI】文心一言的使用

一、获得内测资格&#xff1a; 1、点击网页链接申请&#xff1a;https://yiyan.baidu.com/ 2、点击加入体验&#xff0c;等待通过 二、获得AI伙伴内测名额 1、收到短信通知&#xff0c;点击链接 网页Link&#xff1a;https://chat.baidu.com/page/launch.html?fa&sourc…

LeetCode_Java_2236. 判断根结点是否等于子结点之和

2236. 判断根结点是否等于子结点之和 给你一个 二叉树 的根结点 root&#xff0c;该二叉树由恰好 3 个结点组成&#xff1a;根结点、左子结点和右子结点。 如果根结点值等于两个子结点值之和&#xff0c;返回 true &#xff0c;否则返回 false 。 示例1 输入&#xff1a;roo…