《React后台管理系统实战:九》Redux原理:异步实现【redux-thunk】、redux工具、合并多个reducer函数combineReducers()(三)

本文主要是介绍《React后台管理系统实战:九》Redux原理:异步实现【redux-thunk】、redux工具、合并多个reducer函数combineReducers()(三),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、redux-thunk基础

作用:在 redux 中执行异步任务(ajax, 定时器)

1)安装

cnpm install --save redux-thunk

2)使用:在redux/store.js中

//redux最核心的管理对象: store
import {createStore, applyMiddleware} from 'redux' //【0】引入applyMiddleware
import thunk from 'redux-thunk' // 【1】用来实现redux异步的redux中间件插件
import reducer from './reducer'export default createStore(reducer, applyMiddleware(thunk)) // 【2】创建store对象内部会第一次调用reducer()得到初始状态值

3 ) 在redux/action.js中添加如下

/*
包含n个用来创建action的工厂函数(action creator)*/
import {INCREMENT, DECREMENT} from './action-types'/*
增加的同步action*/
export const increment = number => ({type: INCREMENT, data: number})
/*
减少的同步action: 返回对象*/
export const decrement = number => ({type: DECREMENT, data: number})//【1】增加的异步action: 返回的是函数
export const incrementAsync = number => {return dispatch => {// 1. 执行异步(定时器, ajax请求, promise)setTimeout(() => {// 2. 当前异步任务执行完成时, 分发一个同步actiondispatch(increment(number))}, 1000)}
}

4)components/Counter.jsx

import React, {Component} from 'react'
import PropTypes from 'prop-types'/*
UI组件主要做显示与与用户交互代码中没有任何redux相关的代码*/
export default class Counter extends Component {static propTypes = {count: PropTypes.number.isRequired,increment: PropTypes.func.isRequired,decrement: PropTypes.func.isRequired,incrementAsync: PropTypes.func.isRequired, //【1】接收}constructor(props) {super(props)this.numberRef = React.createRef()}increment = () => {const number = this.numberRef.current.value * 1this.props.increment(number)}decrement = () => {const number = this.numberRef.current.value * 1this.props.decrement(number)}incrementIfOdd = () => {const number = this.numberRef.current.value * 1if (this.props.count % 2 === 1) {this.props.increment(number)}}//【2】异步函数incrementAsync = () => {const number = this.numberRef.current.value * 1this.props.incrementAsync(number)}render() {const count = this.props.countreturn (<div><p>click {count} times</p><div><select ref={this.numberRef}><option value="1">1</option><option value="2">2</option><option value="3">3</option></select> &nbsp;&nbsp;<button onClick={this.increment}>+</button>&nbsp;&nbsp;<button onClick={this.decrement}>-</button>&nbsp;&nbsp;<button onClick={this.incrementIfOdd}>increment if odd</button>&nbsp;&nbsp;<button onClick={this.incrementAsync}>increment async</button></div></div>)}
}

5)containers/App.jsx

import React, {Component} from 'react'
import {connect} from 'react-redux' //引入连接模块
import Counter from '../components/Counter' //引入components下的counter.jsx 注意路径
import {increment, decrement,incrementAsync} from '../redux/actions' //【1】引入redux下的动作incrementAsync// 指定向Counter传入哪些一般属性(属性值的来源就是store中的state)
const mapStateToProps = (state) => ({count: state})
// 指定向Counter传入哪些函数属性
/*如果是函数, 会自动调用得到对象, 将对象中的方法作为函数属性传入UI组件*/
/*const mapDispatchToProps = (dispatch) => ({increment: (number) => dispatch(increment(number)),decrement: (number) => dispatch(decrement(number)),
})*/
/*如果是对象, 将对象中的方法包装成一个新函数, 并传入UI组件 */
const mapDispatchToProps = {increment, decrement}/*
export default connect(mapStateToProps,mapDispatchToProps
)(Counter)*///【2】把incrementAsync添加进去
export default connect(state => ({count: state}),{increment, decrement,incrementAsync},
)(Counter)

效果:

在这里插入图片描述

二、redux开发工具安装

1)下载地址

https://dl.pconline.com.cn/download/2564119-1.html

2)直接拖进浏览器即可

谷歌最新不行就把插件名改为.zip格式解压出来,再到开发中心添加解压后的文件夹即可

3)f12即可看到redux,还不显示则进入4、5步;否则不用进行4、5步

4)安装

cnpm install --save-dev redux-devtools-extension

5)在redux/store.js添加如下

// redux最核心的管理对象: store,
import {createStore, applyMiddleware} from 'redux'
import reducer from './reducer' //导入reducer
import thunk from 'redux-thunk' // 用来实现redux异步的redux中间件插件
import {composeWithDevTools} from 'redux-devtools-extension' //【1】引入工具export default createStore(reducer,composeWithDevTools(applyMiddleware(thunk))) // 【2】再包一层composeWithDevTools();创建store对象内部会第一次调用reducer()得到初始状态值

效果:

在这里插入图片描述

三、combineReducers()合并多个reduce函数

1)在redux/reducer.js中

/*
reducer函数模块: 根据当前state和指定action返回一个新的state*/
import {combineReducers} from 'redux' //【1】引入
import {INCREMENT, DECREMENT} from './action-types'/*
管理count状态数据的reducer*/
function count(state=1, action) {console.log('count()', state, action)switch (action.type) {case INCREMENT:return state + action.datacase DECREMENT:return state - action.datadefault:return state}}const initUser = {}
/*
【2】再写一个状态。管理user状态数据的reducer*/
function user(state = initUser, action) {switch (action.type) {default:return state}
}/*
【3】合并多个状态;combineReducers函数: 接收包含所有reducer函数的对象, 返回一个新的reducer函数(总reducer)
总的reducer函数管理的state的结构{count: 2,user: {}}*/
export default combineReducers({count,user
})

2 ) containers/App.js写法要改成对应的对象

import React, {Component} from 'react'
import {connect} from 'react-redux'import Counter from '../components/Counter'
import {increment, decrement, incrementAsync} from '../redux/actions'// 指定向Counter传入哪些一般属性(属性值的来源就是store中的state)
const mapStateToProps = (state) => ({count: state.count}) //【1】此处对应读取对象的 state.count
// 指定向Counter传入哪些函数属性
/*如果是函数, 会自动调用得到对象, 将对象中的方法作为函数属性传入UI组件*/
/*const mapDispatchToProps = (dispatch) => ({increment: (number) => dispatch(increment(number)),decrement: (number) => dispatch(decrement(number)),
})*/
/*如果是对象, 将对象中的方法包装成一个新函数, 并传入UI组件 */
const mapDispatchToProps = {increment, decrement}/*
export default connect(mapStateToProps,mapDispatchToProps
)(Counter)*/export default connect(state => ({count: state.count}), //【2】此处对应读取对象的 state.count{increment, decrement, incrementAsync},
)(Counter)

这篇关于《React后台管理系统实战:九》Redux原理:异步实现【redux-thunk】、redux工具、合并多个reducer函数combineReducers()(三)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/965210

相关文章

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

SQLite3命令行工具最佳实践指南

《SQLite3命令行工具最佳实践指南》SQLite3是轻量级嵌入式数据库,无需服务器支持,具备ACID事务与跨平台特性,适用于小型项目和学习,sqlite3.exe作为命令行工具,支持SQL执行、数... 目录1. SQLite3简介和特点2. sqlite3.exe使用概述2.1 sqlite3.exe

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

OpenCV实现实时颜色检测的示例

《OpenCV实现实时颜色检测的示例》本文主要介绍了OpenCV实现实时颜色检测的示例,通过HSV色彩空间转换和色调范围判断实现红黄绿蓝颜色检测,包含视频捕捉、区域标记、颜色分析等功能,具有一定的参考... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

HTML5 搜索框Search Box详解

《HTML5搜索框SearchBox详解》HTML5的搜索框是一个强大的工具,能够有效提升用户体验,通过结合自动补全功能和适当的样式,可以创建出既美观又实用的搜索界面,这篇文章给大家介绍HTML5... html5 搜索框(Search Box)详解搜索框是一个用于输入查询内容的控件,通常用于网站或应用程

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.