十七、redux

1. redux理解

1.1. 相关文档

redux中文官网:Redux 中文官网 - JavaScript 应用的状态容器,提供可预测的状态管理。 | Redux 中文官网

中文文档: 自述 · Redux

Github: GitHub - reduxjs/redux: Predictable state container for JavaScript apps

英文文档:https://redux.js.org

Redux - A predictable state container for JavaScript apps. | Redux

先把它装上

npm i redux

在这里插入图片描述

1.2. redux是什么

之前学过vuex,这两个差不多,都是状态管理用的

【Vue】Vuex管理状态入门到实战 - 计数器demo - todoList项目 - 组件间共享数据 - State - Mutation - Action - Getter

【Vue】vuex - 状态自管理应用 - state - view - actions

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

1.3. 什么情况下需要使用redux

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

1.4. redux工作流程

在这里插入图片描述

React Components相当于餐厅的客人客人要吃吃蛋炒饭,Action Creators相当于服务员服务员默默的拿出来点餐软件写上点餐蛋炒饭一份,服务员就按下了点餐软件的发送(相当于dispatch),就把你说的蛋炒饭一份包装成了一个对象action({type:'点餐',data:‘蛋炒饭一份’}),发送给老板(Store)老板盯着电脑屏幕审核完了之后,老板就把action对象就被发送到后厨了(Reducers),第一次交给后厨时候还没有之前的状态,所以传给后厨的previousState是undefined,后厨就明白这个人是第一次点餐,然后就做了一份蛋炒饭,然后蛋炒饭就放在老板面前的台子上了,然后客人取回来(getState())吃。等这个客人再次点菜的时候,唯一区别就是previousState不是undefined了而是蛋炒饭一份。

React Components 一些组件,例如组件里面想在原来的基础上加1操作。

Action Creators 动作创建者,它用来制作动作对象 ( 例如{type:‘+’,data:1} ),然后dispatch把动作对象分发给Store。初学者可以不要Action Creators,可以自己写action对象 ( 例如{type:‘+’,data:1} )。

 action叫做动作对象,例如你加你减你乘你除这些都是动作,动作对象包含你本次动作的类型以及你本次操作的数据,例如加2那么type就是‘+’ data就是2。action不是高大上的东西就是一个object类型的对象,对象里面包含两个固定的属性一个是type一个是data。

dispatch:有分发的意思,dispatch()是一个函数,参数是action。dispatch意思就是把action对象继续往下交,交下去,交给一个能操作状态的人。例如就是有个人真正的给加1,action对象用来交给别人用,dispatch把action交给别人用。

接下来dispatch把action交给了Store,Store是一个特别核心的人,它负责全局的掌控,就像十字路口的交警你停你拐弯,Store是一个指挥者,它本身不干活,就是一个负责调度的人,Reducers才是真正加工状态的人干活的人,只有一个Store,Store就把action对象交给了Reducers让Reducers干活,例如 Reducers看到type是‘+’ data是1然后就在原来的基础上给加1了,Store不仅给Reducers 一个action还给一个previousState叫做之前的状态,用来存储原来的值,所以上面才能在原来的基础上加1。Reducers把交给它的状态计算加工完了(例如在原来的基础上+1),然后返回一个新的状态交给了Store。然后在组件(React Components )里面用getState()就可以得到Reducers交给Store的状态(计算结果)。

Reducers能干两件事,第一件事是初始化状态,第二件事就上面的那个加工状态。初始化时候Store传给Reducers的previousState是undefined,action是有的。等第二次传给Reducers时候previousState就不是undefined了就有值了。因为第一次初始化时候上一次的状态是没有的所以previousState是undefined。

初始化时候的type是{type:@@init@@},初始化时候data是没有的。

Reducers帮忙初始化时候,type的加减乘除是人家内置给写好的,例如初始化@@init@@,data不传,然后Reducers发现是@@init@@,你既然是初始化我已经给你准备好了,把0交出去。你初始化的是多少你要和Reducers对话,例如是99,那么就在初始化的时候告诉Reducers我的值是99。

2. redux的三个核心概念

2.1. action

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

2.2. reducer

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

2.3. store

  1. stateactionreducer联系在一起的对象

  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时, 自动调用

3. API

3.1. createStore()

作用:创建包含指定reducerstore对象

3.2. store对象

  1. 作用: redux库最核心的管理对象
  2. 它内部维护着:
    1. state
    2. reducer
  3. 核心方法:
    1. getState()
    2. dispatch(action)
    3. subscribe(listener)
  4. 具体编码:
    1. store.getState()
    2. store.dispatch({type:'INCREMENT', number})
    3. store.subscribe(render)

3.3. applyMiddleware()

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

3.4. combineReducers()

作用:合并多个reducer函数

4. 使用redux编写应用

4.1 效果

在这里插入图片描述

纯React实现求和

 component/Count/index.jsx

import React, { Component } from 'react'

export default class Count extends Component {
  state={count:0}
  //加
  increment=()=>{
    //现在获取的值
    const {value}=this.selectNumber
    //原来的count值
    const {count}=this.state
    this.setState({count:count+value*1})//因为获取到的值是字符串,乘以1就转换为数字了
  }

  //减
  decrement=()=>{
   //现在获取的值
   const {value}=this.selectNumber
   //原来的count值
   const {count}=this.state
   this.setState({count:count-value*1})//因为获取到的值是字符串,乘以1就转换为数字了
  }

  //当前求和为奇数再加
  incrementIfOdd=()=>{
   //现在获取的值
   const {value}=this.selectNumber
   //原来的count值
   const {count}=this.state
   if(count % 2 !==0){//除2取余不等于0就是奇数
    this.setState({count:count+value*1})//因为获取到的值是字符串,乘以1就转换为数字了
   }
  }

  //异步加
  incrementAsync=()=>{
    //现在获取的值
    const {value}=this.selectNumber
    //原来的count值
    const {count}=this.state
    setTimeout(() => {
        this.setState({count:count+value*1})//因为获取到的值是字符串,乘以1就转换为数字了
    }, 500);
  }



  render() {
    return (
      <div>
        <h1>当前求和为:{this.state.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>
      </div>
    )
  }
}

App.js

import React, { Component } from 'react'
import Count from './component/Count'

export default class App extends Component {
  render() {
    return (
      <div>
          <Count/>
      </div>
    )
  }
}

求和Redux实现精简版(精简版没有Action creators)

每一个组件都要有一个自己的Reducer,比如有个组件A,A想把自己的状态交给redux,那就要为A组件构建一个Reducer。如果有个B组件,也想把状态交给redux,那就要为B组件构建一个Reducer。所以人家叫Reducers有s是复数意思就是可以多个。那一会就写两个文件,一个是store.js,一个是count_reducer.js(为count组件初始化和加工状态的reducer)。整个应用只有一个store。

新建一个文件夹redux,所有和redux相关的文件都放到这个里面。

 安装 npm i redux

redux/store.js

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

*/

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

export default createStore(countReducer)

redux/count_reducer.js

/*
1、该文件是用于创建一个为Count组件服务的reducer,reducer的本质就是一个函数。
2、reducer函数会接到两个参数,分别是:之前的状态(preState),动作对象(action)。

页面初始化时候store会自动调用一次countReducer进行状态的初始化,传入的参数为 preState为undefined   action为{type: '@@redux/INITt.b.a.i.9.s'}
*/

const initState=0 //初始化状态,也可以是对象initState={},但是这里不需要用对象
export default function countReducer(preState=initState,action){//参数preState=0
    console.log(preState,action);//页面加载时候 undefined {type: '@@redux/INITt.b.a.i.9.s'}
    //从action对象中获取:type、data
    const {type,data}=action
    switch (type){
        case 'increment'://如果是加
            return preState+data
        case 'decrement'://如果是减
            return preState+data 
        
        default:
            return preState
            //return 0 //页面初始化时候store.js就会做一件事,醒醒reducer,我给你发一个action我不说加也不说减告诉你你去初始化而且data还不给你,就会传入action,preState为undefined,所以default这里初始化
    }
}

component/Count/index.jsx入口文件

import React, { Component } from 'react'
//引入store用于获取redux中的状态
import store from '../../redux/store'

export default class Count extends Component {
  state={count:0}

  /*
  不在这里写了,在入口文件index.js中写
  componentDidMount(){
    //检测redux中状态的变化,只要变化,就调用render
    store.subscribe(()=>{
      this.setState({})//更新状态后render就会被调用
    })
  } */

  //加
  increment=()=>{
    //现在获取的值
    const {value}=this.selectNumber
    //原来的count值
    //const {count}=this.state
    //this.setState({count:count+value*1})//因为获取到的值是字符串,乘以1就转换为数字了
    
    store.dispatch({type:'increment',data:value*1})
  
  }

  //减
  decrement=()=>{
   //现在获取的值
   const {value}=this.selectNumber
   //原来的count值
   //const {count}=this.state
   //this.setState({count:count-value*1})//因为获取到的值是字符串,乘以1就转换为数字了
   store.dispatch({type:'decrement',data:value*1})
  
  }

  //当前求和为奇数再加
  incrementIfOdd=()=>{
   //现在获取的值
   const {value}=this.selectNumber
   //原来的count值
   //const {count}=this.state
   const count=store.getState()
   if(count % 2 !==0){//除2取余不等于0就是奇数
    //this.setState({count:count+value*1})//因为获取到的值是字符串,乘以1就转换为数字了
      store.dispatch({type:'increment',data:value*1})
    }
  }

  //异步加
  incrementAsync=()=>{
    //现在获取的值
    const {value}=this.selectNumber
    //原来的count值
    //const {count}=this.state
    setTimeout(() => {
        //this.setState({count:count+value*1})//因为获取到的值是字符串,乘以1就转换为数字了
        store.dispatch({type:'increment',data: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>
      </div>
    )
  }
}

入口文件index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import store from './redux/store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

store.subscribe(()=>{
  root.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
  
})

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

求和Redux实现(完整版)

4.2 实现

redux/store.js

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

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

redux/count_reducer.js

该文件是用于创建一个为Count组件服务的reducer,reducer的本质就是一个函数
reducer函数会接到两个参数,分别为:之前的状态(preState),动作对象(action)

import {INCREMENT,DECREMENT} from './constant'

const initState = 0 //初始化状态
export default function countReducer(preState=initState,action){
  // console.log(preState);
  //从action对象中获取:type、data
  const {type,data} = action
  //根据type决定如何加工数据
  switch (type) {
    case INCREMENT: //如果是加
      return preState + data
    case DECREMENT: //若果是减
      return preState - data
    default:
      return preState
  }
}

redux/count_action.js

该文件专门为Count组件生成action对象

import {INCREMENT,DECREMENT} from './constant'

//箭头函数返回一个对象需要用小括号括起来({type:INCREMENT,data})
export const createIncrementAction = data => ({type:INCREMENT,data})
export const createDecrementAction = data => ({type:DECREMENT,data})

redux/constant.js

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

export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'

Count/index.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 {

  /* componentDidMount(){
    //检测redux中状态的变化,只要变化,就调用render
    store.subscribe(()=>{
      this.setState({})
    })
  } */

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

index.js

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

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

// 监测redux中状态的改变,如redux的状态发生了改变,那么重新渲染App组件
store.subscribe(()=>{
	ReactDOM.render(<App/>,document.getElementById('root'))
})

4.3 总结

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

  2. count_reducer.js:

    1. reducer的本质是一个函数,接收:preState,action,返回加工后的状态
    2. reducer有两个作用:初始化状态,加工状态
    3. reducer被第一次调用时,是store自动触发的,
      传递的preState是undefined,
      传递的action是:{type:'@@REDUX/INIT_a.2.b.4}
  3. 在index.js中监测store中状态的改变,一旦发生改变重新渲染<App/>
    备注:redux只负责管理状态,至于状态的改变驱动着页面的展示,要靠我们自己写。

完整版新增文件:

  1. count_action.js 专门用于创建action对象
  2. constant.js 放置容易写错的type值

5. redux异步编程

 action除了可以是一般对象,还可以是第二种值就是函数。管一般对象的action叫做同步action,管函数类型的action叫做异步action。action是同步还是异步看它的值是对象还是函数。

上面原来异步是在组件中写的,需要打开着页面等待500毫秒,现在不想在组件中等500毫秒,用异步action,把等的动作交给action,也就是把等的动作交给服务员。

5.1理解

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

5.2. 使用异步中间件

npm install redux-thunk

在这里插入图片描述

count_action.js

该模块专门为Count组件生成action对象

异步action,就是指action的值为函数,异步action中一般都会调用同步action,异步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)=>{//dispatch不需要引入import store......,因为参数里面把dispatch已经传进来了,用下图的写法也是可以的
		setTimeout(()=>{
			dispatch(createIncrementAction(data))
		},time)
	}
}

 

store.js

该模块专门用于暴露一个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中的代码片段

component/Count/index.jsx

 

 

5.3 总结

  1. 明确:延迟的动作不想交给组件自身,想交给action
  2. 何时需要异步action:想要对状态进行操作,但是具体的数据靠异步任务返回。
  3. 具体编码:
    1. npm install redux-thunk,并配置在store中
    2. 创建action的函数不再返回一般对象,而是一个函数,该函数中写异步任务。
    3. 异步任务有结果后,分发一个同步的action去真正操作数据。
  4. 备注:异步action不是必须要写的,完全可以自己等待异步任务的结果了再去分发同步action。

6. react-redux

6.1. 理解

  1. 一个React插件库
  2. 专门用来简化React应用中使用redux

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

  1. UI组件

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

    1. 负责管理数据和业务逻辑,不负责UI的呈现
    2. 使用 Redux 的 API
    3. 一般保存在containers文件夹下

模型图

在这里插入图片描述

容器组件可以随意的和redux打交道,可以使用任何redux的api。但是UI组件不可以,UI组件只是做界面的呈现绑定一些事件的监听写一些逻辑。但凡和redux打交道的地方都要用容器组件去做。

容器组件包裹着UI组件。

容器组件放在container文件夹中,UI组件放在component文件夹中。

容器组件要连接UI组件连接redux。

其实就是把redux的操作都写到容器组件中去了,在UI组件中直接props用就可以了,容器组件是连接redux和UI组件的桥梁。

react-redux需要上面写的代码和安装的库,redux库等,是接着上面章节那些写的,连在一起的。

6.3. 相关API

  1. Provider:让所有组件都可以得到state数据

  2. connect:用于包装 UI 组件生成容器组件

  3. mapStateToprops:将外部的数据(即state对象)转换为UI组件的标签属性

  4. mapDispatchToProps:将分发action的函数转换为UI组件的标签属性

6.4 基本使用

安装

npm install react-redux

在这里插入图片描述

 在这里插入图片描述

components/Count/index.jsx

UI组件

import React, { Component } from 'react'

export default class Count extends Component {
  //加法
  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>
    )
  }
}

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'

/* 
目的是把状态传递给UI组件的props,参数是状态,react-redux在调用这个函数的时候已经把state传进去了,不需要引入import store...也不需要store.getState()得到状态。state是redux中的状态,react-redux给这个函数传进去了。

  1.mapStateToProps函数返回的是一个对象;
  2.返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value,目的是把状态给带过去。
  3.mapStateToProps用于传递状态
*/
function mapStateToProps(state){
  return {count:state}
}

/* 
目的是把操作状态的方法传递给UI组件的props,参数是redux的dispatch方法,是react-redux在调用这个函数的时候把dispatch给这个函数传进去的。操作状态的方法是redux的,按理说应该引入import store...,然后store.dispatch(),但是这个函数参数已经给了dispatch了,直接用就可以了
  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的容器组件,connect()()意思就是调用一次的返回值还是函数继续调用
export default connect(mapStateToProps,mapDispatchToProps)(CountUI)

App.jsx

给容器组件传递store

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>
    )
  }
}

Count组件

 忘了传500毫秒了

 

总结

  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,也可以是一个对象【优化1】

6.5 优化

先优化容器组件

优化1 简写mapDispatchToProps

//使用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的简写,只要提供action,react-redux能自动分发就像调用了 dispatch()但是不需要自己调用,这是api层面的优化。
  {
    jia:createIncrementAction,
    jian:createDecrementAction,
    jiaAsync:createIncrementAsyncAction,
  }
)(CountUI)

优化2 Provider

容器组件可以检测redux中的状态改变(用上react-redux之后就不用自己检测了,所有的逻辑都藏在了connect调用,调用connect之后就默认有了监测redux的能力,不用在index.js中写了),并渲染页面,所以不需要在index.js中检测了
不要在App.jsx中给子组件传递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'

//Provider  整个应用里面有需要store的地方我都给你传进去,可以把store给全部的容器组件传过去,而不用像原来一样在App.js中一个一个传
ReactDOM.render(
	<Provider store={store}>
		<App/>
	</Provider>,
	document.getElementById('root')
)

优化3 整合UI组件和容器组件

每个组件两个文件夹太麻烦了,直接整合在一起就好了~

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.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的一般写法
  /* 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)

总结

  1. 容器组件和UI组件整合一个文件
  2. 无需自己给容器组件传递store,给<App/>包裹一个<Provider store={store}>即可。
  3. 使用了react-redux后也不用再自己检测redux中状态的改变了,容器组件可以自动完成这个工作。
  4. mapDispatchToProps也可以简单的写成一个对象
  5. 一个组件要和redux“打交道”要经过哪几步?
    1. 定义好UI组件—不暴露
    2. 引入connect生成一个容器组件,并暴露,写法如下:

connect(
	state => ({key:value}), //映射状态
	{key:xxxxxAction} //映射操作状态的方法
)(UI组件)

                3、在UI组件中通过this.props.xxxxxxx读取和操作状态

6.6 数据共享版

多个组件共享状态

在这里插入图片描述

 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";

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

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

总结

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

7. 使用上redux调试工具

7.1 安装chrome浏览器插件

Redux Dev Tools

7.2 下载工具依赖包

npm install redux-devtools-extension

在这里插入图片描述

 

 在store中进行配置

import {composeWithDevTools} from 'redux-devtools-extension'
const store = createStore(allReducer,composeWithDevTools(applyMiddleware(thunk)))

 

8. 纯函数和高阶函数

reducer要求是一个纯函数,所以操作数组的时候,不能用push之类的方法

8.1 纯函数

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

8.2 高阶函数

  1. 理解: 一类特别的函数
    1. 情况1: 参数是函数
    2. 情况2: 返回是函数
  2. 常见的高阶函数:
    1. 定时器设置函数
    2. 数组的forEach()/map()/filter()/reduce()/find()/bind()
    3. promise
    4. react-redux中的connect函数
  3. 作用: 能实现更加动态, 更加可扩展的功能

9. 最终版

  1. 所有变量名字要规范,尽量触发对象的简写形式。
  2. reducers文件夹中,编写index.js专门用于汇总并暴露所有的reducer

在这里插入图片描述

 containers/Count/index.jsx

import React, { Component } from 'react'
//引入action
import {
  increment,
  decrement,
  incrementAsync
} from '../../redux/actions/count'
//引入connect用于连接UI组件与redux
import {connect} from 'react-redux'

//定义UI组件
class Count extends Component {

  //加法
  increment = ()=>{
    const {value} = this.selectNumber
    this.props.increment(value*1)
  }
  //减法
  decrement = ()=>{
    const {value} = this.selectNumber
    this.props.decrement(value*1)
  }
  //奇数再加
  incrementIfOdd = ()=>{
    const {value} = this.selectNumber
    if(this.props.count % 2 !== 0){
      this.props.increment(value*1)
    }
  }
  //异步加
  incrementAsync = ()=>{
    const {value} = this.selectNumber
    this.props.incrementAsync(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 => ({//这个state 就是多个组件的总的状态,所以state.count,state.persons.length
    count:state.count,
    personCount:state.persons.length
  }),
  {increment,decrement,incrementAsync}
)(Count)

containers/Person/index.jsx

import React, { Component } from 'react'
import {nanoid} from 'nanoid'
import {connect} from 'react-redux'
import {addPerson} from '../../redux/actions/person'

class Person extends Component {

  addPerson = ()=>{
    const name = this.nameNode.value
    const age = this.ageNode.value*1
    const personObj = {id:nanoid(),name,age}
    this.props.addPerson(personObj)
    this.nameNode.value = ''
    this.ageNode.value = ''
  }

  render() {
    return (
      <div>
        <h2>我是Person组件,上方组件求和为{this.props.count}</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.persons.map((p)=>{
              return <li key={p.id}>{p.name}--{p.age}</li>
            })
          }
        </ul>
      </div>
    )
  }
}

export default connect(
  state => ({//这个state就是多个组件的总的状态,所以state.persons,state.count
    persons:state.persons,
    count:state.count
  }),//映射状态
  {addPerson}//映射操作状态的方法
)(Person)

redux/actions/count.js

/* 
  该文件专门为Count组件生成action对象
*/
import { INCREMENT, DECREMENT } from "../constant";

//同步action,就是指action的值为Object类型的一般对象
export const increment = (data) => ({ type: INCREMENT, data });
export const decrement = (data) => ({ type: DECREMENT, data });

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

redux/action/person.js

import { ADD_PERSON } from "../constant";

//创建增加一个人的action动作对象
export const addPerson = (personObj) => ({ type: ADD_PERSON, data: personObj });

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、data
  const { type, data } = action;
  //根据type决定如何加工数据
  switch (type) {
    case INCREMENT: //如果是加
      return preState + data;
    case DECREMENT: //若果是减
      return preState - data;
    default:
      return preState;
  }
}

redux/reducers/person.js

import { ADD_PERSON } from "../constant";

//初始化人的列表
const initState = [{ id: "001", name: "tom", age: 18 }];

export default function personReducer(preState = initState, action) {
  const { type, data } = action;
  switch (type) {
    case ADD_PERSON: //若是添加一个人
      //preState.unshift(data) //此处不可以这样写,这样会导致preState被改写了,personReducer就不是纯函数了。
      return [data, ...preState];
    default:
      return preState;
  }
}

redux/reducers/index.js

/* 
	该文件用于汇总所有的reducer为一个总的reducer
*/
//引入combineReducers,用于汇总多个reducer
import { combineReducers } from "redux";
//引入为Count组件服务的reducer
import count from "./count";
//引入为Person组件服务的reducer
import persons from "./person";

//汇总所有的reducer变为一个总的reducer,combineReducers({})参数传入的对象就是多个组件状态的总的reduce ,就是redux保存的总的状态对象,用key才能找到某个组件保存的的状态。
export default combineReducers({
  count,//是简写,其实是count:count
  persons,//是简写,其实是persons:persons
});

汇总的reducer,combineReducers({})参数{}里面保存这总的状态对象:

 

redux/constant.js

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

redux/store.js

/* 
	该文件专门用于暴露一个store对象,整个应用只有一个store对象
*/
//引入createStore,专门用于创建redux中最为核心的store对象
import { createStore, applyMiddleware } from "redux";
//引入汇总之后的reducer
import reducer from "./reducers";
//引入redux-thunk,用于支持异步action
import thunk from "redux-thunk";
//引入redux-devtools-extension
import { composeWithDevTools } from "redux-devtools-extension";

//暴露store
export default createStore(
  reducer,
  composeWithDevTools(applyMiddleware(thunk))
);

App.jsx

import React, { Component } from 'react'
import Count from './containers/Count' //引入的Count的容器组件
import Person from './containers/Person' //引入的Person的容器组件

export default class App extends Component {
  render() {
    return (
      <div>
        <Count/>
        <hr/>
        <Person/>
      </div>
    )
  }
}

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包裹App,目的是让App所有的后代容器组件都能接收到store */
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

展示

在这里插入图片描述

10. 项目运行打包

npm run build

在这里插入图片描述

 

serve能让指定文件夹快速成为服务器根目录开启服务器,

全局安装serve

npm i serve -g

serve 回车在当前文件夹快速开启一个服务器

或者serve 目录名

例如serve a      意思就当前目录下的a目录成为服务器的根目录。

运行

serve -s build

-s是可以省略的,就是当前目录下的build目录为服务器的根目录。

【React】redux - 三大核心概念 - action - reducer - store - 异步编程 - react-redux - 调试工具 - 纯函数 - 高阶函数_YK菌的博客-CSDN博客_react reducer store

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值