Redux&&React-redux

目录

redux

学习文档

redux是什么

什么情况下需要使用redux

 redux工作流程

 redux的三个核心概念

action

reducer

store

求和案例_redux精简版

求和案例_redux完整版

求和案例_redux异步action版

. redux的核心API

react-redux  

react-redux  原理

 . react-Redux将所有组件分成两大类

连接容器组件于ui组件        

react-redux 基本使用

react-redux基本使用 总结

react-redux优化

简写mapDispatchToProps

provideer组件优化

整合ui组件与容器组件

优化总结

数据共享

编写person组件

编写person组件的reducer

完成数据共享

数据共享总结

纯函数和高阶函数

纯函数

. 高阶函数

redux调试工具


redux

学习文档

  1. 英文文档: Redux - A predictable state container for JavaScript apps. | Redux
  2. 中文文档: Redux中文文档

redux是什么

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

什么情况下需要使用redux

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

 redux工作流程

举例: 可以看做一个餐厅客人点餐(react components),服务员(actionCreators)通过点餐宝(dispath)发给老板(store),老板通知后厨做饭(reducers) 后厨加工完给老板 客人取餐

  1. react components :组件 
  2. actionCreators :创建动作对象(type类型(字符串),data值) 
  3. dispath(action):通知仓库
  4. store: 仓库(调度者):接收action对象通知reducers(之前值 | |undefined,要处理的值)处理数据
  5. reducers: 处理数据(把处理后的状态给store),reducers可以初始化状态
  6. react components getState从仓库拿数据

 redux的三个核心概念

action

  1. 动作的对象
  2. 包含2个属性
    1. type:标识属性, 值为字符串, 唯一, 必要属性
    2. data:数据属性, 值类型任意, 可选属性
  3. 例子:{ type: 'ADD_STUDENT',data:{name: 'tom',age:18} }

reducer

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

store

  1. stateactionreducer联系在一起的对象
  2. 如何得到此对象?
    1. import {createStore} from 'redux'
    2. import reducer from './reducers'
    3. const store = createStore(reducer)
  3. 此对象的功能?
    1. getState(): 得到state
    2. subscribe(listener): 注册监听, 当产生了新的state时, 自动调用
    3. dispatch(action): 分发action, 触发reducer调用, 产生新的state

求和案例_redux精简版

去除Count组件自身的状态

src下建立:

-redux  (-store.js,-count_reducer.js)

store.js:

  • 1).引入redux中的createStore函数,创建一个store
  • 2).createStore调用时要传入一个为其服务的reducer
  •  3).记得暴露store对象
/* 
	该文件专门用于暴露一个store对象,整个应用只有一个store对象
*/

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

.count_reducer.js:

1).reducer的本质是一个函数,接收:preState,action,返回加工后的状态

2).reducer有两个作用:初始化状态,加工状态

3).reducer被第一次调用时,是store自动触发的,

  •  传递的preState是undefined,
  • 传递的action是:{type:'@@REDUX/INIT_a.2.b.4}
/* 
	1.该文件是用于创建一个为Count组件服务的reducer,reducer的本质就是一个函数
	2.reducer函数会接到两个参数,分别为:之前的状态(preState),动作对象(action)
*/

const initState = 0 //初始化状态
export default function countReducer(preState = initState, action) {
	// console.log(preState, action); store自动调用reducer 创建初始值 action{type: "@@redux/INIT7.x.8.5.b" data:''}
	//从action对象中获取:type、data
	const { type, data } = action
	//根据type决定如何加工数据
	switch (type) {
		case 'increment': //如果是加
			return preState + data
		case 'decrement': //若果是减
			return preState - data
		default:
			return preState
	}
}

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

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

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'

ReactDOM.render(<App/>,document.getElementById('root'))

store.subscribe(()=>{
	ReactDOM.render(<App/>,document.getElementById('root'))
})

求和案例_redux完整版

新增文件:

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

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

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

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

求和案例_redux异步action版

对象类型的为同步,函数类型的为异步(因为函数里面可以开启异步任务)

  1. redux默认是不能进行异步处理的,
  2. 某些时候应用中需要在redux中执行异步任务(ajax, 定时器)

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

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

(3).具体编码:

  •  1).yarn add redux-thunk,并配置在store中
  •   2).创建action的函数不再返回一般对象,而是一个函数,该函数中写异步任务。
  •   3).异步任务有结果后,分发一个同步的action去真正操作数据。

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

store

  • 引入中间件 redux-thunk让store可以识别异步的action(函数)
  • 执行中间件applyMiddleware当做创建仓库的第二个参数 applyMiddleware(thunk)
/* 
	该文件专门用于暴露一个store对象,整个应用只有一个store对象
*/

//引入createStore,专门用于创建redux中最为核心的store对象
import {createStore,applyMiddleware} from 'redux'
//引入为Count组件服务的reducer
import countReducer from './count_reducer'
//引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
//暴露store
export default createStore(countReducer,applyMiddleware(thunk))

 count_action.js

异步action中一般都会调用同步action,异步action不是必须要用的。


//异步action,就是指action的值为函数,异步action中一般都会调用同步action,异步action不是必须要用的。
export const createIncrementAsyncAction = (data,time) => {
	return (dispatch)=>{
		setTimeout(()=>{
			dispatch(createIncrementAction(data))
		},time)
	}
}

. redux的核心API

 createstore() 作用:创建包含指定reducer的store对

store对象  作用: redux库最核心的管理对象

  1. 它内部维护着: state   reducer
  2. 核心方法:   获取getState()    监听subscribe(listener)    派发dispatch(action)
  3. 具体编码: store.getState()   store.subscribe(render)     store.dispatch({type:'INCREMENT', number})

applyMiddleware  作用:应用上基于redux的中间件(插件库) 异步中使用

 combineReducers() 作用:合并多个reducer函数

react-redux  

  1. Provider:让所有组件都可以得到state数据
  2. connect:用于包装 UI 组件生成容器组件
  3. mapStateToprops:将外部的数据(即state对象)转换为UI组件的标签属性
  4. mapDispatchToProps:将分发action的函数转换为UI组件的标签属性

react-redux  原理

 . react-Redux将所有组件分成两大类

  1. UI组件
    1. 只负责 UI 的呈现,不带有任何业务逻辑
    2. 通过props接收数据(一般数据和函数)
    3. 不使用任何 Redux  API
    4. 一般保存在components文件夹下
  2. 容器组件
    1. 负责管理数据和业务逻辑,不负责UI的呈现
    2. 使用 Redux  API
    3. 一般保存在containers文件夹下

连接容器组件于ui组件        

创建容器组件,容器组件要连接ui组件和仓库

react-redux 引入connect用于连接UI组件与redux

使用connect()()创建并暴露一个Count的容器组件(前者为仓库 接收两个函数 返回值做为状态传递给了UI组件,(函数1设置状态,函数2设置操作状态的方法) 后者为ui组件)

//引入Count的UI组件
import CountUI from '../../components/Count'
//引入connect用于连接UI组件与redux
import {connect} from 'react-redux'

//使用connect()()创建并暴露一个Count的容器组件
export default connect()(CountUI)

仓库不能直接在容器组件中导入,要通过父及传递给容器组件

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 基本使用

 containers 容器组件

mapStateToProps 映射状态传递给组件

    1.mapStateToProps函数返回的是一个对象;

    2.返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value

    3.mapStateToProps用于传递状态

mapDispatchToProps映射 设置状态的方法传递给组件

     1.mapDispatchToProps函数返回的是一个对象;

    2.返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value

    3.mapDispatchToProps用于传递操作状态的方法

//引入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的value
	3.mapStateToProps用于传递状态
*/
function mapStateToProps(state){
	return {count:state}
}

/* 
	1.mapDispatchToProps函数返回的是一个对象;
	2.返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value
	3.mapDispatchToProps用于传递操作状态的方法
*/
function mapDispatchToProps(dispatch){
	return {
		jia:number => dispatch(createIncrementAction(number)),
		jian:number => dispatch(createDecrementAction(number)),
		jiaAsync:(number,time) => dispatch(createIncrementAsyncAction(number,time)),
	}
}

//使用connect()()创建并暴露一个Count的容器组件
export default connect(mapStateToProps,mapDispatchToProps)(CountUI)

components ui组件

通过 this.props 接收容器组件(父组件)传递的状态和方法

import React, { Component } from 'react'

export default class Count extends Component {

	state = {carName:'奔驰c63'}

	//加法
	increment = ()=>{
		const {value} = this.selectNumber
		this.props.jia(value*1)
	}
	//减法
	decrement = ()=>{
		const {value} = this.selectNumber
		this.props.jian(value*1)
	}
	//奇数再加
	incrementIfOdd = ()=>{
		const {value} = this.selectNumber
		if(this.props.count % 2 !== 0){
			this.props.jia(value*1)
		}
	}
	//异步加
	incrementAsync = ()=>{
		const {value} = this.selectNumber
		this.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>
		)
	}
}

react-redux基本使用 总结

(1).明确两个概念:

  •   1).UI组件:不能使用任何redux的api,只负责页面的呈现、交互等。
  •    2).容器组件:负责和redux通信,将结果交给UI组件。

 (2).如何创建一个容器组件————靠react-redux 的 connect函数

  •  connect(mapStateToProps,mapDispatchToProps)(UI组件)
  •   mapStateToProps:映射状态,返回值是一个对象
  • mapDispatchToProps:映射操作状态的方法,返回值是一个对象

 (3).备注1:容器组件中的store是靠props传进去的,而不是在容器组件中直接引入

 (4).备注2:mapDispatchToProps,也可以是一个对象

react-redux优化

简写mapDispatchToProps

写对象格式react-redux会自动派发一个函数通知 reducer 自动传递参数

	//mapDispatchToProps的简写
	{
		jia:createIncrementAction,
		jian:createDecrementAction,
		jiaAsync:createIncrementAsyncAction,
	}

provideer组件优化

使用了react-redux会自动监听数据的变化不在使用 store.subscribe

有多个容器组件需要仓库时不用在父组件传递使用provideer

import store from './redux/store'
import {Provider} from 'react-redux'

ReactDOM.render(
	<Provider store={store}>
		<App/>
	</Provider>,
	document.getElementById('root')
)

整合ui组件与容器组件

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.selectNumber
		this.props.jia(value * 1)
	}
	//减法
	decrement = () => {
		const { value } = this.selectNumber
		this.props.jian(value * 1)
	}
	//奇数再加
	incrementIfOdd = () => {
		const { value } = this.selectNumber
		if (this.props.count % 2 !== 0) {
			this.props.jia(value * 1)
		}
	}
	//异步加
	incrementAsync = () => {
		const { value } = this.selectNumber
		this.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的简写
	{
		jia: createIncrementAction,
		jian: createDecrementAction,
		jiaAsync: createIncrementAsyncAction,
	}
)(Count)

优化总结

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

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

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

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

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

  • (1).定义好UI组件---不暴露
  •  (2).引入connect生成一个容器组件,并暴露,写法如下:                                   
  • (3).在UI组件中通过this.props.xxxxxxx读取和操
connect(

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

       {key:xxxxxAction} //映射操作状态的方法
 )(UI组件)
import React, { Component } from 'react'
import { connect } from "react-redux";
import { createIncrementAction } from "../../redux/count_action";

class Count extends Component {
	render() {
		return (
			<div>
				<h2>当前求和为{this.props.he}</h2>
				<button onClick={this.add} >点我加1</button>
			</div>
		)
	}
	add = () => {
		//通知redux加1
		this.props.jiafa(1)

	}
}
export default connect(
	// 映射状态
	state => ({ he: state }),

	// 映射操作状态的方法
	{ jiafa: createIncrementAction }
)(Count)

数据共享

编写person组件

import React, { Component } from 'react'

export default class index extends Component {
    render() {
        return (
            <div>
                <h2>我是person组件</h2>
                <input ref={c => this.nameNode = c} type="text" placeholder='输入名字' />
                <input ref={c => this.ageNode = c} type="text" placeholder='输入年龄' />
                <button>添加</button>
                <ul>
                    <li>名字1--年龄1</li>
                    <li>名字1--年龄1</li>
                    <li>名字1--年龄1</li>
                </ul>
            </div>
        )

    }
    addPerson = () => {
        const name = this.nameNode.value
        const age = this.ageNode.value
    }
}

编写person组件的reducer


定义action对象中type类型的常量值
export const ADD_PERSON = 'add_person'



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


person组件服务的reducer
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 } = action
    switch (type) {
        case ADD_PERSON: //若是添加一个人
            return [data, ...preState]
        default:
            return preState
    }
}

完成数据共享

store.js

现在redux 存储的是多个状态 应该使用 combineReducers 合并为一个对象        

/* 
	该文件专门用于暴露一个store对象,整个应用只有一个store对象
*/

//引入createStore,专门用于创建redux中最为核心的store对象
import { createStore, applyMiddleware, combineReducers } from 'redux'
//引入为Count组件服务的reducer
import countReducer from './reducers/count'
//引入为person组件服务的reducer
import personReducer from './reducers/person'
//引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'

//汇总所有的reducer变为一个总的reducer
const allReducer = combineReducers({
	he: countReducer,
	rens: personReducer
})

//暴露store
export default createStore(allReducer, applyMiddleware(thunk))

person.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 {
    render() {
        return (
            <div>
                <h2>我是person组件</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.ren.map(p => {

                        return <li key={p.id}>{p.name}--年龄{p.age}</li>
                    })}

                </ul>
            </div>
        )

    }
    addPerson = () => {
        const name = this.nameNode.value
        const age = this.ageNode.value
        const personObj = { id: nanoid(), name, age }
        this.props.jiaren(personObj)
    }
}
export default connect(
    state => ({ ren: state.rens }),//映射状态
    { jiaren: createAddPersonAction }//映射修改状态的方法
)(Person)

组件数据互通

count取出人数的长度展示

	state => ({
		count: state.he,
		renshu: state.rens.length
	}),
	<h2>我是Count组件,下方组件总人数为:{this.props.renshu}</h2>

prson组件展示求和

export default connect(
    state => ({
        ren: state.rens,
        he: state.he
    }),//映射状态
    { jiaren: createAddPersonAction }//映射修改状态的方法
)(Person)
   <h2>我是person组件,上方求和{this.props.he}</h2>

数据共享总结

 (1).定义一个Pserson组件,和Count组件通过redux共享数据。

(2).为Person组件编写:reducer、action,配置constant常量。

(3).重点:Person的reducer和Count的Reducer要使用combineReducers进行合并,合并后的总状态是一个对象!!!

(4).交给store的是总reducer,最后注意在组件中取出状态的时候,记得“取到位”。

纯函数和高阶函数

纯函数

  1. 一类特别的函数: 只要是同样的输入(实参),必定得到同样的输出(返回)
  2. 必须遵守以下一些约束  
    1. 不得改写参数数据
    2. 不会产生任何副作用,例如网络请求,输入和输出设备
    3. 不能调用Date.now()或者Math.random()等不纯的方法  
  3. reduxreducer函数必须是一个纯函数
  4. redux比较的是空间地址

. 高阶函数

  1. 理解: 一类特别的函数
    1. 情况1: 参数是函数
    2. 情况2: 返回是函数
  2. 常见的高阶函数:
    1. 定时器设置函数
    2. 数组的forEach()/map()/filter()/reduce()/find()/bind()
    3. promise
    4. react-redux中的connect函数
  3. 作用: 能实现更加动态, 更加可扩展的功能
export default function personReducer(preState = initState, action) {
    // console.log('personReducer@#@#@#');
    const { type, data } = action
    switch (type) {
        case ADD_PERSON: //若是添加一个人
            // preState.unshift(data)此处不可以这样写,这样导致preState被改写了,personReducer就不是纯函数了
            return [data, ...preState]
        default:
            return preState
    }
}

redux调试工具

安装 :npm install --save-dev redux-devtools-extension

(1).yarn add redux-devtools-extension

(2).store中进行配置     

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值