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

Redux

Redux

redux是什么?

  • redux是一个专门用于做状态管理的JS库(不是react插件库)
  • 它可以用在react,angular,vue等项目中,但基本与react配合使用
  • 作用:集中式管理react应用中多个组件共享的状态

什么情况下需要使用redux

  • 某个组件的状态,需要让其他组件可以随时拿到(共享)
  • 一个组件需要改变另一个组件的状态
  • 总体原则:能不用就不用,如果不用比较吃力才考虑使用

redux工作流程

redux的三个核心概念

action

1.动作的对象

2.包含两个属性:

  • type:标识属性,值为字符串,唯一,必要属性
  • data:数据属性,值类型任意,可选属性

 3.例子:{type:'ADD_STUDENT',data:{name:'tom',age:18}}

reducer

  1. 用于初始化状态,加工状态
  2. 加工时,根据旧的state和action,产生新的state的纯函数

store

1.将state,action,reducer联系在一起的对象

2.如何得到此对象?

  1. import {createStore} from 'redux'
  2. import reducer from './reducers'
  3. const store=createStore(reducer)

3.此对象的功能

  1. getState():得到state
  2. dispatch(action):分发action,触发reducer调用,产生新的state
  3. subscribe(listener):注册监听,当产生了新的state时,自动调用

redux的核心API

1.createstore():创建包含指定reducer的store对象

2.store对象

  • 作用:redux库最核心的管理对象
  • 它内部维护者state,reducer

3.核心方法:

  • getState()
  • dispatch(action)
  • subscribe(listener)

具体编码:

  1. store.getState()
  2. store.dispatch({type:'INCREMENT',number})
  3. store.subscribe(render)

4.applyMiddleware():应用上基于redux的中间件(插件库)

5.combineReducers():合并多个reducer函数

redux实现求和案例

完整版代码

redux/constant.js

/* 该文件专门为Count组件生成action对象
*/
import {INCREMENT,DECREMENT} from './constant'export const createIncrementAction = data => ({type:INCREMENT,data})
export const createDecrementAction = data => ({type:DECREMENT,data})

redux/count_action.js

/* 该模块是用于定义action对象中type类型的常量值,目的只有一个:便于管理的同时防止程序员单词写错
*/
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'

redux/count_reducer.js

/* 1.该文件是用于创建一个为Count组件服务的reducer,reducer的本质就是一个函数2.reducer函数会接到两个参数,分别为:之前的状态(preState),动作对象(action)
*/
import {INCREMENT,DECREMENT} from './constant'const initState = 0 //初始化状态
export default function countReducer(preState=initState,action){// console.log(preState);//从action对象中获取:type、dataconst {type,data} = action//根据type决定如何加工数据switch (type) {case INCREMENT: //如果是加return preState + datacase DECREMENT: //若果是减return preState - datadefault:return preState}
}

redux/store.js

/* 该文件专门用于暴露一个store对象,整个应用只有一个store对象
*///引入createStore,专门用于创建redux中最为核心的store对象
import {createStore} from 'redux'
//引入为Count组件服务的reducer
import countReducer from './count_reducer'
//暴露store
export default createStore(countReducer)

Count,.jsx

import React, { Component } from 'react'
//引入store,用于获取redux中保存状态
import store from '../../redux/store'
//引入actionCreator,专门用于创建action对象
import {createIncrementAction,createDecrementAction} from '../../redux/count_action'export default class Count extends Component {state = {carName:'奔驰c63'}/* componentDidMount(){//检测redux中状态的变化,只要变化,就调用renderstore.subscribe(()=>{this.setState({})})} *///加法increment = ()=>{const {value} = this.selectNumberstore.dispatch(createIncrementAction(value*1))}//减法decrement = ()=>{const {value} = this.selectNumberstore.dispatch(createDecrementAction(value*1))}//奇数再加incrementIfOdd = ()=>{const {value} = this.selectNumberconst count = store.getState()if(count % 2 !== 0){store.dispatch(createIncrementAction(value*1))}}//异步加incrementAsync = ()=>{const {value} = this.selectNumbersetTimeout(()=>{store.dispatch(createIncrementAction(value*1))},500)}render() {return (<div><h1>当前求和为:{store.getState()}</h1><select ref={c => this.selectNumber = c}><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>&nbsp;<button onClick={this.increment}>+</button>&nbsp;<button onClick={this.decrement}>-</button>&nbsp;<button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>&nbsp;<button onClick={this.incrementAsync}>异步加</button>&nbsp;</div>)}
}

求和案例_redux

1.去除Count组件自身的状态

2.src下建立:redux/store.js,redux/count_reducer.js

3.store.js

  1. 引入redux中的createStore函数,创建一个store
  2. createStore调用时要传入一个为其服务的reducer
  3. 记得暴露store对象

4.count_reducer.js

  1. reducer的本质上是一个函数,接收:preState,action返回加工后的状态
  2. reducer有两个作用:初始化状态,加工状态
  3. reducer被第一次调用时,是store自动触发的,传递的preState是undefined,传递的action是{type:'@@REDUX/INIT_a.2.b.1'}

5.在index.js中监测store中状态的改变,一旦发生改变重新渲染<App/>

备注:redux只负责管理状态,至于状态的改变驱动着页面的展示,要靠我们自己写

6.count_action.js:专门用于创建action对象

7.constant.js:放置容易写错的type值 

异步action

	//异步加incrementAsync = ()=>{const {value} = this.selectNumber// setTimeout(()=>{store.dispatch(createIncrementAsyncAction(value*1,500))// },500)}
//异步action,就是指action的值为函数,异步action中一般都会调用同步action,异步action不是必须要用的。
export const createIncrementAsyncAction = (data,time) => {return (dispatch)=>{setTimeout(()=>{dispatch(createIncrementAction(data))},time)}
}
//引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
//暴露store
export default createStore(countReducer,applyMiddleware(thunk))

1.明确:延迟的动作不想交给组件自身,想交给action

2.何时需要异步action:想要对状态进行操作,但是具体的数据靠异步任务返回

3.具体编码:

1).yarn add redux-thunk,并配置在store中

2).创建action的函数不再返回一般对象,而是一个函数,该函数中写异步任务。

3).异步任务有结果后,分发一个同步的action去真正操作数据。

4.备注:异步action不是必须要写的, 完全可以自己等待异步任务的结果了再去分发同步action

 react-redux

1.所有的UI组件都应该包裹一个容器组件,它们是父子关系

2.容器组件是真正和redux打交道的,里面可以随意使用redux的api

3.UI组件中不能使用任何redux的api

4.容器组件会传递给UI组件:

  1. redux中所保存的状态
  2. 用于操作状态的方法

5.备注:容器给UI传递:状态,操作状态的方法,均通过props传递

react-redux基本使用

1.明确两个概念:

2.UI组件:不能使用任何redux的api,只负责页面的呈现,交互等

3.容器组件:负责和redux通信,将结果交给UI组件

4.如何创建一个容器组件---靠react-redux的connect函数

                connect(mapStateToProps,mapDispatchToProps)(UI组件)

                -mapStateToProps:映射状态,返回值是一个对象

                -mapDispatchToProps:映射操作状态的方法,返回值是一个对象

备注:

  • 容器组件中的store是靠props传进去的,而不是在容器组件中直接引入
  • mapDispatchToProps,也可以是一个对象

containers/Count/index.jsx

//引入Count的UI组件
import CountUI from '../../components/Count'
//引入action
import {createIncrementAction,createDecrementAction,createIncrementAsyncAction
} from '../../redux/count_action'//引入connect用于连接UI组件与redux
import {connect} from 'react-redux'/* 1.mapStateToProps函数返回的是一个对象;2.返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value3.mapStateToProps用于传递状态
*/
function mapStateToProps(state){return {count:state}
}/* 1.mapDispatchToProps函数返回的是一个对象;2.返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value3.mapDispatchToProps用于传递操作状态的方法
*/
function mapDispatchToProps(dispatch){return {jia:number => dispatch(createIncrementAction(number)),jian:number => dispatch(createDecrementAction(number)),jiaAsync:(number,time) => dispatch(createIncrementAsyncAction(number,time)),}
}//使用connect()()创建并暴露一个Count的容器组件,conect传递的两个参数要为函数
export default connect(mapStateToProps,mapDispatchToProps)(CountUI)

components/Count/index.jsx

import React, { Component } from 'react'export default class Count extends Component {state = {carName:'奔驰c63'}//加法increment = ()=>{const {value} = this.selectNumberthis.props.jia(value*1)}//减法decrement = ()=>{const {value} = this.selectNumberthis.props.jian(value*1)}//奇数再加incrementIfOdd = ()=>{const {value} = this.selectNumberif(this.props.count % 2 !== 0){this.props.jia(value*1)}}//异步加incrementAsync = ()=>{const {value} = this.selectNumberthis.props.jiaAsync(value*1,500)}render() {//console.log('UI组件接收到的props是',this.props);return (<div><h1>当前求和为:{this.props.count}</h1><select ref={c => this.selectNumber = c}><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>&nbsp;<button onClick={this.increment}>+</button>&nbsp;<button onClick={this.decrement}>-</button>&nbsp;<button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>&nbsp;<button onClick={this.incrementAsync}>异步加</button>&nbsp;</div>)}
}

App组件中给Count传递store props参数

import React, { Component } from 'react'
import Count from './containers/Count'
import store from './redux/store'export default class App extends Component {render() {return (<div>{/* 给容器组件传递store */}<Count store={store} /></div>)}
}

react-redux优化

1.容器组件和UI组件整合一个文件

2.无需自己给容器组件传递store,给<App/>包裹一个<Provider store={store}>即可

在入口文件index.js中如下操作

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'
import {Provider} from 'react-redux'ReactDOM.render(<Provider store={store}><App/></Provider>,document.getElementById('root')
)

3.使用了react-redux后也不用再自己检测redux中状态的改变了,容器组件可以自动完成这个工作

4.mapDispatchToProps也可以简单的写成一个对象

5.一个组件要和redux打交道要经过哪几步?

              (1).定义好UI组件---不暴露

              (2).引入connect生成一个容器组件,并暴露,写法如下:

                  connect(

                    state => ({key:value}), //映射状态

                    {key:xxxxxAction} //映射操作状态的方法

                  )(UI组件)

              (4).在UI组件中通过this.props.xxxxxxx读取和操作状态

containers/Count/index.jsx

import React, { Component } from 'react'
//引入action
import {createIncrementAction,createDecrementAction,createIncrementAsyncAction
} from '../../redux/count_action'
//引入connect用于连接UI组件与redux
import {connect} from 'react-redux'//定义UI组件
class Count extends Component {state = {carName:'奔驰c63'}//加法increment = ()=>{const {value} = this.selectNumberthis.props.jia(value*1)}//减法decrement = ()=>{const {value} = this.selectNumberthis.props.jian(value*1)}//奇数再加incrementIfOdd = ()=>{const {value} = this.selectNumberif(this.props.count % 2 !== 0){this.props.jia(value*1)}}//异步加incrementAsync = ()=>{const {value} = this.selectNumberthis.props.jiaAsync(value*1,500)}render() {//console.log('UI组件接收到的props是',this.props);return (<div><h1>当前求和为:{this.props.count}</h1><select ref={c => this.selectNumber = c}><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>&nbsp;<button onClick={this.increment}>+</button>&nbsp;<button onClick={this.decrement}>-</button>&nbsp;<button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>&nbsp;<button onClick={this.incrementAsync}>异步加</button>&nbsp;</div>)}
}//使用connect()()创建并暴露一个Count的容器组件
export default connect(state => ({count:state}),//mapDispatchToProps的一般写法/* dispatch => ({jia:number => dispatch(createIncrementAction(number)),jian:number => dispatch(createDecrementAction(number)),jiaAsync:(number,time) => dispatch(createIncrementAsyncAction(number,time)),}) *///mapDispatchToProps的简写{jia:createIncrementAction,jian:createDecrementAction,jiaAsync:createIncrementAsyncAction,}
)(Count)

react-redux---数据共享版

  1. 定义一个Person组件,和Count组件通过redux共享数据
  2. 为Person组件编写:reducer,action,配置constant常量
  3. 重点:Person的reducer和Count的Reducer要使用combineReducers进行合并
  4. 交给store的是总reducer,最后注意在组件中取出状态的时候,记得"取到位"

纯函数

1.一类特别的函数:只要是同样的输入(实参),必定得到同样的输出(返回)

2.必须遵守以下一些约束:

  • 不得改写参数数据
  • 不会产生任何副作用,例如网络请求,输入和输出设备
  • 不能调用Date.now()或者Math.random()等不纯的方法

3.redux的reducer函数必须是一个纯函数

react-redux开发者工具的使用

      (1).yarn add redux-devtools-extension

      (2).store中进行配置

          import {composeWithDevTools} from 'redux-devtools-extension'

          const store = createStore(allReducer,composeWithDevTools(applyMiddleware(thunk)))

src/index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'
import {Provider} from 'react-redux'ReactDOM.render(<Provider store={store}><App/></Provider>,document.getElementById('root')
)

src/App.jsx

import React, { Component } from 'react'
import Count from './containers/Count'
import Person from './containers/Person'export default class App extends Component {render() {return (<div><Count/><hr/><Person/></div>)}
}

src/containers/Count/index.jsx

import React, { Component } from 'react'
//引入action
import {createIncrementAction,createDecrementAction,createIncrementAsyncAction
} from '../../redux/actions/count'
//引入connect用于连接UI组件与redux
import {connect} from 'react-redux'//定义UI组件
class Count extends Component {state = {carName:'奔驰c63'}//加法increment = ()=>{const {value} = this.selectNumberthis.props.jia(value*1)}//减法decrement = ()=>{const {value} = this.selectNumberthis.props.jian(value*1)}//奇数再加incrementIfOdd = ()=>{const {value} = this.selectNumberif(this.props.count % 2 !== 0){this.props.jia(value*1)}}//异步加incrementAsync = ()=>{const {value} = this.selectNumberthis.props.jiaAsync(value*1,500)}render() {//console.log('UI组件接收到的props是',this.props);return (<div><h2>我是Count组件,下方组件总人数为:{this.props.renshu}</h2><h4>当前求和为:{this.props.count}</h4><select ref={c => this.selectNumber = c}><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>&nbsp;<button onClick={this.increment}>+</button>&nbsp;<button onClick={this.decrement}>-</button>&nbsp;<button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>&nbsp;<button onClick={this.incrementAsync}>异步加</button>&nbsp;</div>)}
}//使用connect()()创建并暴露一个Count的容器组件
export default connect(state => ({count:state.he,renshu:state.rens.length}),{jia:createIncrementAction,jian:createDecrementAction,jiaAsync:createIncrementAsyncAction,}
)(Count)

src/containers/Person/index.jsx

import React, { Component } from 'react'
import {nanoid} from 'nanoid'
import {connect} from 'react-redux'
import {createAddPersonAction} from '../../redux/actions/person'class Person extends Component {addPerson = ()=>{const name = this.nameNode.valueconst age = this.ageNode.value*1const personObj = {id:nanoid(),name,age}this.props.jiaYiRen(personObj)this.nameNode.value = ''this.ageNode.value = ''}render() {return (<div><h2>我是Person组件,上方组件求和为{this.props.he}</h2><input ref={c=>this.nameNode = c} type="text" placeholder="输入名字"/><input ref={c=>this.ageNode = c} type="text" placeholder="输入年龄"/><button onClick={this.addPerson}>添加</button><ul>{this.props.yiduiren.map((p)=>{return <li key={p.id}>{p.name}--{p.age}</li>})}</ul></div>)}
}export default connect(state => ({yiduiren:state.rens,he:state.he}),//映射状态{jiaYiRen:createAddPersonAction}//映射操作状态的方法
)(Person)

src/redux/constant.js

/* 该模块是用于定义action对象中type类型的常量值,目的只有一个:便于管理的同时防止程序员单词写错
*/
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
export const ADD_PERSON = 'add_person'

src/redux/store.js

/* 该文件专门用于暴露一个store对象,整个应用只有一个store对象
*///引入createStore,专门用于创建redux中最为核心的store对象
import {createStore,applyMiddleware,combineReducers} from 'redux'
//引入为Count组件服务的reducer
import countReducer from './reducers/count'
//引入为Count组件服务的reducer
import personReducer from './reducers/person'
//引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
//引入redux-devtools-extension
import {composeWithDevTools} from 'redux-devtools-extension'//汇总所有的reducer变为一个总的reducer
const allReducer = combineReducers({he:countReducer,rens:personReducer
})//暴露store 
export default createStore(allReducer,composeWithDevTools(applyMiddleware(thunk)))

src/redux/actions/count.js

/* 该文件专门为Count组件生成action对象
*/
import {INCREMENT,DECREMENT} from '../constant'//同步action,就是指action的值为Object类型的一般对象
export const createIncrementAction = data => ({type:INCREMENT,data})
export const createDecrementAction = data => ({type:DECREMENT,data})//异步action,就是指action的值为函数,异步action中一般都会调用同步action,异步action不是必须要用的。
export const createIncrementAsyncAction = (data,time) => {return (dispatch)=>{setTimeout(()=>{dispatch(createIncrementAction(data))},time)}
}

src/redux/actions/person.js

import {ADD_PERSON} from '../constant'//创建增加一个人的action动作对象
export const createAddPersonAction = personObj => ({type:ADD_PERSON,data:personObj})

src/redux/reducers/count.js

/* 1.该文件是用于创建一个为Count组件服务的reducer,reducer的本质就是一个函数2.reducer函数会接到两个参数,分别为:之前的状态(preState),动作对象(action)
*/
import {INCREMENT,DECREMENT} from '../constant'const initState = 0 //初始化状态
export default function countReducer(preState=initState,action){// console.log('countReducer@#@#@#');//从action对象中获取:type、dataconst {type,data} = action//根据type决定如何加工数据switch (type) {case INCREMENT: //如果是加return preState + datacase DECREMENT: //若果是减return preState - datadefault:return preState}
}

src/redux/reducers/person.js

import {ADD_PERSON} from '../constant'//初始化人的列表
const initState = [{id:'001',name:'tom',age:18}]export default function personReducer(preState=initState,action){// console.log('personReducer@#@#@#');const {type,data} = actionswitch (type) {case ADD_PERSON: //若是添加一个人//preState.unshift(data) //此处不可以这样写,这样会导致preState被改写了,personReducer就不是纯函数了。return [data,...preState]default:return preState}
}

相关文章:

  • electron 无边框常用配置 实测 禁止缩放 设置大小 设置主副屏 关闭窗口 重启 主副进程联动 自动更新等
  • 分布式事务Seata的4种模式详解
  • ES6模块化简明笔记
  • clone plugin搭建MySQL 8.0 主从复制
  • [linux][命令]linux文件操作命令大全
  • 11. Rancher2.X部署多案例镜像
  • Eclipse 运行配置
  • 【连续4届EI检索,SPIE 出版】第五届信号处理与计算机科学国际学术会议(SPCS 2024,8月23-25)
  • 【nginx 第二篇章】各个环境安装 nginx
  • 将 Tcpdump 输出内容重定向到 Wireshark
  • 数据结构——栈的讲解(超详细)
  • vLLM CPU和GPU模式署和推理 Qwen2 等大语言模型详细教程
  • 求职 day13总结
  • 将电脑打造成私人网盘,支持外网访问之详细操作教程
  • Vue3学习笔记第一天
  • 【Leetcode】104. 二叉树的最大深度
  • Android 初级面试者拾遗(前台界面篇)之 Activity 和 Fragment
  • canvas绘制圆角头像
  • JavaScript 是如何工作的:WebRTC 和对等网络的机制!
  • Java到底能干嘛?
  • PHP变量
  • python 装饰器(一)
  • React as a UI Runtime(五、列表)
  • tab.js分享及浏览器兼容性问题汇总
  • 百度贴吧爬虫node+vue baidu_tieba_crawler
  • 关于springcloud Gateway中的限流
  • 前端设计模式
  • 如何使用Mybatis第三方插件--PageHelper实现分页操作
  • 使用阿里云发布分布式网站,开发时候应该注意什么?
  • 温故知新之javascript面向对象
  • 用jquery写贪吃蛇
  • 东超科技获得千万级Pre-A轮融资,投资方为中科创星 ...
  • 如何在 Intellij IDEA 更高效地将应用部署到容器服务 Kubernetes ...
  • #laravel 通过手动安装依赖PHPExcel#
  • $.each()与$(selector).each()
  • ( 用例图)定义了系统的功能需求,它是从系统的外部看系统功能,并不描述系统内部对功能的具体实现
  • (30)数组元素和与数字和的绝对差
  • (C语言)输入一个序列,判断是否为奇偶交叉数
  • (DenseNet)Densely Connected Convolutional Networks--Gao Huang
  • (ibm)Java 语言的 XPath API
  • (PWM呼吸灯)合泰开发板HT66F2390-----点灯大师
  • (STM32笔记)九、RCC时钟树与时钟 第二部分
  • (二)PySpark3:SparkSQL编程
  • (附源码)ssm旅游企业财务管理系统 毕业设计 102100
  • (附源码)ssm智慧社区管理系统 毕业设计 101635
  • (个人笔记质量不佳)SQL 左连接、右连接、内连接的区别
  • (函数)颠倒字符串顺序(C语言)
  • (十八)用JAVA编写MP3解码器——迷你播放器
  • (转)平衡树
  • (轉貼) 2008 Altera 亞洲創新大賽 台灣學生成果傲視全球 [照片花絮] (SOC) (News)
  • **CI中自动类加载的用法总结
  • ... fatal error LINK1120:1个无法解析的外部命令 的解决办法
  • .java 指数平滑_转载:二次指数平滑法求预测值的Java代码
  • .net core + vue 搭建前后端分离的框架
  • .net core 源码_ASP.NET Core之Identity源码学习