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

react 09之状态管理工具1 redux+ react-thunk的使用实现跨组件状态管理与异步操作

目录

  • react 09之状态管理工具1 redux+ react-thunk的使用实现跨组件状态管理与异步操作
    • store / index.js store的入口文件
    • index.js 在项目入口文件 引入
    • store / actionType.js 定义action的唯一标识
    • store / reducers / index.js
    • store / actions / form.js
    • store / reducers / form.js
    • store / actions / list.js
    • store / reducers / list.js
    • 使用 App类.jsx
    • ASon.jsx
    • 效果

react 09之状态管理工具1 redux+ react-thunk的使用实现跨组件状态管理与异步操作

  • npm install redux react-redux

  • npm i redux-thunk

  • redux-thunk

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

store / index.js store的入口文件

import { applyMiddleware, legacy_createStore } from 'redux';
// 引入redux-thunk,用于支持异步action
import reduxThunk from 'redux-thunk';
// 引入汇总后的reducer
import reducers from './reducers';const store = legacy_createStore(reducers, applyMiddleware(reduxThunk))
export default store;

index.js 在项目入口文件 引入

import App from "./7redux/2使用thunk/App类";
import store from "./store/index.js";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Provider store={store}><App /></Provider>
);

store / actionType.js 定义action的唯一标识

// 常量 唯一标识 标记当前action的唯一性
export const FORM_ADD_COUNT = 'form_addCount'
export const FORM_SUB_COUNT = 'form_subCount'
export const LIST_ADD_LIST = 'list_addList'

store / reducers / index.js

/*该文件用于汇总所有的reducer为一个总的reducer
*/
//引入combineReducers,用于汇总多个reducer
import { combineReducers } from "redux";
//引入为form组件服务的reducer
import form from "./form";
//引入为list组件服务的reducer
import list from "./list";//汇总所有的reducer变为一个总的reducer
export default combineReducers({form,list,
});

store / actions / form.js

/*该文件专门为Form组件生成相关action对象
*/
import { FORM_ADD_COUNT, FORM_SUB_COUNT } from "../actionType";export const form_addCount = (data) => ({ type: FORM_ADD_COUNT, data });
export const form_subCount = (data) => ({ type: FORM_SUB_COUNT, data });export const formAddAsync = (data) => {return (dispatch) => {setTimeout(() => {dispatch(form_addCount(data));}, 2000);};
};

store / reducers / form.js

import { FORM_ADD_COUNT, FORM_SUB_COUNT } from "../actionType";
/*** form组件的reducer*/
// 初始状态
let initSate = {count: 0
};
export default function formReducer(state = initSate, 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;}
}

store / actions / list.js

/*该文件专门为List组件生成相关action对象
*/
import { LIST_ADD_LIST } from "../actionType";// 同步action
export const list_addList = (data) => ({ type: LIST_ADD_LIST, data });

store / reducers / list.js

import { LIST_ADD_LIST } from '../actionType'// 初始状态
const initSate = {list:[]
}export default function listReducer(state=initSate,action){switch(action.type){case LIST_ADD_LIST:return {...state,list:[...state.list,action.data]}default:return state}
}

使用 App类.jsx

import React, { Component } from 'react';
import { connect } from "react-redux";
import { formAddAsync, form_addCount, form_subCount } from "../../store/actions/form";
import { list_addList } from "../../store/actions/list";
import ASon from "./ASon";
class App extends Component {state = {}componentDidMount() {}render(){// console.log('111',this.props);const { count,list } = this.propsconst addList = ()=>{let str = list && list.length ? '我是' + (list.length + 1) : '我是1'let arr = []arr.push(str)this.props.list_addList(arr)}return (<div>app<p>Count: {count}</p><button onClick={this.props.form_addCount}>Increment</button><button onClick={this.props.form_subCount}>Decrement</button><button onClick={this.props.formAddAsync}>异步add</button><div>----</div><ASon></ASon><div>----</div><div>{list ? list.map((item,idx)=>{return (<div key={idx}>{item}</div>)}) : ''}<button onClick={addList}>addList</button></div></div>)}
}// 拿到redux的值
const mapStateToProps = (state) => {return {count: state.form.count,list: state.list.list,};
};
// 拿到redux 所触发的
const mapDispatchToProps = {form_addCount,form_subCount,formAddAsync,list_addList
}
export default connect(mapStateToProps, mapDispatchToProps)(App);

ASon.jsx

import React from 'react';
import { connect } from "react-redux";
import { form_addCount } from "../../store/actions/form";
const ASon = (props) => {return (<div className='content'>ASon 组件 count-{props.count} <br/><button onClick={props.form_addCount}>Increment</button></div>)
}// 拿到redux的值
const mapStateToProps = (state) => {return {count: state.form.count};
};
// 拿到redux 所触发的
const mapDispatchToProps = {form_addCount,
}
export default connect(mapStateToProps, mapDispatchToProps)(ASon);

效果

在这里插入图片描述

在这里插入图片描述

http://www.lryc.cn/news/123362.html

相关文章:

  • opencv实战项目 手势识别-实现尺寸缩放效果
  • Netty对HPACK头部压缩的支持
  • C++:替换string中的字符
  • 【ChatGPT】自我救赎
  • 微信小程序(由浅到深)
  • 冒泡排序 简单选择排序 插入排序 快速排序
  • linux文件I/O之 open() 函数用法
  • 用Java操作MySQL数据库
  • SpringBoot启动报错:java: 无法访问org.springframework.boot.SpringApplication
  • Vue3 setup语法糖 解决富文本编辑器上传图片64位码过长问题 quill-image-extend-module
  • 百度坐标(BD09)、国测局坐标(火星坐标,GCJ02)、和WGS84坐标系之间的转换
  • 论文浅尝 | CI4MRC:基于因果推断去除机器阅读理解中的名字偏差
  • 【校招VIP】测试计划之黑盒测试白盒测试
  • 学习笔记整理-JS-01-语法与变量
  • PHP之PHPExcel
  • Redis系列(一):深入了解Redis数据类型和底层数据结构
  • javaScript:如何获取html中的元素对象
  • 面试总结-webpack/git
  • 深入解析美颜SDK:算法、效果与实现
  • ChatGPT Plus和ChatGPT对比
  • 计算机网络 运输层 TCP连接建立、释放
  • npm run xxx 的时候发生了什么?(以npm run dev举例说明)
  • 图解结构体大小和位域例子
  • 游戏行业实战案例 5 :玩家在线分布
  • TypeScript 关于对【泛型】的定义使用解读
  • 盛元广通食品药品检验检测实验室LIMS系统
  • 【数据结构】-- 栈和队列
  • 使用SpringAop切面编程通过Spel表达式实现Controller权限控制
  • Flutter:简单搞一个内容高亮
  • 2023/08/10