Redux

Redux理解

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

文档

英文文档    中文文档    Github

需要使用Redux的情况

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

redux工作流程

redux原理图

求和案例

GIF 2022-6-2 11-39-08.gif

纯React版

Count组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import React, { Component } from 'react'

export default class Count extends Component {

state = {count: 0}

// 加法
increment = () => {
const {value} = this.selectedNumber
const {count} = this.state
this.setState({count: count + +value})
}
// 减法
decrement = () => {
const {value} = this.selectedNumber
const {count} = this.state
this.setState({count: count - +value})
}
// 奇数时加
incrementIfOdd = () => {
const {value} = this.selectedNumber
const {count} = this.state
if (count % 2 !== 0) {
this.setState({count: count + +value})
}
}
// 异步加
incrementAsync = () => {
const {value} = this.selectedNumber
const {count} = this.state
setTimeout(() => {
this.setState({count: count + +value})
}, 500)
}
render() {
return (
<>
<h1>当前求和为:{this.state.count}</h1>
<select ref={c => this.selectedNumber = c}>
<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}>add if odd</button>&nbsp;&nbsp;
<button onClick={this.incrementAsync}>add async</button>
</>
)
}
}

Redux精简版

两个文件,三个API,不使用Action Creator

结构

store.js用于暴露一个store对象,(整个应用只有一个store对象)

1
2
3
4
5
6
7
8
9
10
/*
该文件专门用于暴露一个store对象,整个应用只有一个store对象
*/

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

export default legacy_createStore(countReducer)

xx_reducer.js用于创建一个为组件服务的reducer
reducer第一次被调用时,是store自动触发的,传递的preState是undefined

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* 
该文件用于创建一个为Count组件服务的reducer,reducer的本质是一个函数
reducer函数会接到两个参数,分别为:preState之前的状态、action动作对象
reducer返回加工后的状态
*/

const initState = 0
export default function countReducer(preState=initState, action) {
// 从action对象中获取type和data
const { type, data } = action
// 根据type决定如何加工数据
switch (type) {
case 'increment':
return preState + data
case 'decrement':
return preState - data
default:
return preState
}
}

Count组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import React, { Component } from 'react'
// 引入store,用户获取redux中保存的状态
import store from '../../redux/store'

export default class Count extends Component {

// state = {count: 0}
state = {}

componentDidMount() {
// 检测redux中状态的变化,一旦变化即调用render
store.subscribe(() => {
this.setState({}) // 只要执行setState(),即使不改变状态数据,组件也会重新render()
})
}

// 加法
increment = () => {
const {value} = this.selectedNumber
store.dispatch({type: 'increment', data: +value})
}
// 减法
decrement = () => {
const {value} = this.selectedNumber
store.dispatch({type: 'decrement', data: +value})
}
// 奇数时加
incrementIfOdd = () => {
const {value} = this.selectedNumber
const count = store.getState()
if (count % 2 !== 0) {
store.dispatch({type: 'increment', data: +value})
}
}
// 异步加
incrementAsync = () => {
const {value} = this.selectedNumber
setTimeout(() => {
store.dispatch({type: 'increment', data: +value})
}, 500)
}
render() {
return (
<>
<h1>当前求和为:{store.getState()}</h1>
<select ref={c => this.selectedNumber = c}>
<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}>add if odd</button>&nbsp;&nbsp;
<button onClick={this.incrementAsync}>add async</button>
</>
)
}
}

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

1
2
3
4
5
6
7
8
9
10
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常量

1
2
3
4
/* 该模块用于定义action对象中type类型的常量值,便于管理同时防止单词写错 */

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

新增文件xx_action.js,创建action对象

1
2
3
4
5
6
7
/* 该文件专门为Count组件生成action对象 */

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

export const createIncrementAction = data => ({type: INCREMENT, data})

export const createDecrementAction = data => ({type: DECREMENT, data})

Count组件中这样写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 加法
increment = () => {
const {value} = this.selectedNumber
store.dispatch(createIncrementAction(+value))
}
// 减法
decrement = () => {
const {value} = this.selectedNumber
store.dispatch(createDecrementAction(+value))
}
// 奇数时加
incrementIfOdd = () => {
const {value} = this.selectedNumber
const count = store.getState()
if (count % 2 !== 0) {
store.dispatch(createIncrementAction(+value))
}
}
// 异步加
incrementAsync = () => {
const {value} = this.selectedNumber
setTimeout(() => {
store.dispatch(createIncrementAction(+value))
}, 500)
}

异步action

延迟的动作不想交给组件自身,想交给action

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

  • action为Object类型的一般对象:同步action
  • action为function函数:异步action

创建action的函数不再返回一般对象,而是一个函数,该函数中写异步任务。异步任务有结果后,分发一个同步的action去真正操作数据。

异步action不是必须要写的,完全可以自己等待异步任务的结果后再去分发同步action。

store.js

1
2
3
4
5
6
7
8
9
10
11
12
/*
该文件专门用于暴露一个store对象,整个应用只有一个store对象
*/

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

export default legacy_createStore(countReducer, applyMiddleware(thunk))

action.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* 该文件专门为Count组件生成action对象 */

import { INCREMENT, DECREMENT } from "./constant"
// import store from "./store"

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

export const createDecrementAction = data => ({type: DECREMENT, data})

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

React-Redux

将React组件与Redux尽可能地剥离,让UI组件与容器组件间通过props传递,便于项目后期的更新与维护

react-redux模型图

连接容器组件与UI组件

Count组件删除所有与redux有关的内容,作为UI组件

建立containers文件夹,存放Count的容器组件,基础代码如下:

1
2
3
4
5
6
7
8
// 引入Count的UI组件
import CountUI from '../../components/Count'

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

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

App组件中,引入Count的容器组件,并将store作为props传递:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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>
)
}
}

求和案例

image.png

容器组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 引入Count的UI组件
import CountUI from '../../components/Count'

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

// 引入action
import {
createDecrementAction,
createIncrementAction,
createIncrementAsyncAction
} from '../../../src/redux/count_action'

/*
mapStateToProps函数返回的是一个对象
返回的对象中的key就作为传递给UI组件props的key,value作为props的value
用于传递状态
*/
function mapStateToProps(state) {
return {count: state}
}
/*
mapDispatchToProps函数返回的是一个对象
返回的对象中的key就作为传递给UI组件props的key,value作为props的value
用于传递操作状态的方法
*/
function mapDispatchToProps(dispatch) {
// 通知redux执行加法
return {
increment: data => dispatch(createIncrementAction(data)),
decrement: data => dispatch(createDecrementAction(data)),
incrementAsync: (data, time) => dispatch(createIncrementAsyncAction(data, time))
}
}

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

UI组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import React, { Component } from 'react'

export default class Count extends Component {

// state = {count: 0}
state = {}

// 加法
increment = () => {
const {value} = this.selectedNumber
this.props.increment(+value)
}
// 减法
decrement = () => {
const {value} = this.selectedNumber
this.props.decrement(+value)
}
// 奇数时加
incrementIfOdd = () => {
const {value} = this.selectedNumber
if (this.props.count % 2 !== 0) {
this.props.increment(+value)
}
}
// 异步加
incrementAsync = () => {
const {value} = this.selectedNumber
this.props.incrementAsync(+value, 500)
}
render() {
return (
<>
<h1>当前求和为:{this.props.count}</h1>
<select ref={c => this.selectedNumber = c}>
<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}>add if odd</button>&nbsp;&nbsp;
<button onClick={this.incrementAsync}>add async</button>
</>
)
}
}
  1. 明确两个概念:
    1. UI组件:不能使用任何redux的api,只负责页面的呈现、交互等
    2. 容器组件:负责和redux通信,将结果交给UI组件
  2. 如何创建一个容器组件——靠react-reduxconnect函数
    • connect(mapStateToProps, mapDispatchToProps)(UI组件)
    • mapStateToProps: 映射状态,返回值是一个对象
    • mapDispatchToProps: 映射操作状态的方法,返回值是一个对象
  3. 容器组件中的store是靠props传进去的,而不是在容器组件中直接引入
  4. mapDispatchToProps也可以是一个对象

优化

简写mapDispatchToProps

mapDispatchToProps也可以写成一个对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 编码方式的优化
export default connect(
state => ({count: state}),
// mapDispatchToProps的一般写法
/* dispatch => ({
increment: data => dispatch(createIncrementAction(data)),
decrement: data => dispatch(createDecrementAction(data)),
incrementAsync: data => dispatch(createIncrementAsyncAction(data, 500))
}) */
// mapDispatchToProps的简写
{
increment: createIncrementAction,
decrement: createDecrementAction,
incrementAsync: createIncrementAsyncAction
}
)(CountUI)

Provider组件

  • 使用react-redux后,index.js中不再需要监听store的改变
  • 使用Provider组件后,App组件中不再需要给组件传递store

index.js修改如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from "react"
import ReactDOM from "react-dom"
import { Provider } from "react-redux"
import App from "./App"
import store from "./redux/store"


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

整合UI组件与容器组件

将Count组件的UI组件与容器组件整合在一起,默认暴露容器组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// 引入connect用于连接UI组件与redux
import { connect } from 'react-redux'
// 引入action
import {
createDecrementAction,
createIncrementAction,
createIncrementAsyncAction
} from '../../../src/redux/count_action'
import React, { Component } from 'react'

class Count extends Component {

// state = {count: 0}
state = {}

// 加法
increment = () => {
const {value} = this.selectedNumber
this.props.increment(+value)
}
// 减法
decrement = () => {
const {value} = this.selectedNumber
this.props.decrement(+value)
}
// 奇数时加
incrementIfOdd = () => {
const {value} = this.selectedNumber
if (this.props.count % 2 !== 0) {
this.props.increment(+value)
}
}
// 异步加
incrementAsync = () => {
const {value} = this.selectedNumber
this.props.incrementAsync(+value, 500)
}
render() {
return (
<>
<h1>当前求和为:{this.props.count}</h1>
<select ref={c => this.selectedNumber = c}>
<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}>add if odd</button>&nbsp;&nbsp;
<button onClick={this.incrementAsync}>add async</button>
</>
)
}
}

export default connect(
state => ({count: state}),
{
increment: createIncrementAction,
decrement: createDecrementAction,
incrementAsync: createIncrementAsyncAction
}
)(Count)

优化总结

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

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

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

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

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

    1. 定义好UI组件—不暴露

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

      1
      2
      3
      4
      connect(
      state => ({key:state}), //映射状态
      {key:xxxxxAction} //映射操作状态的方法
      )(UI组件)
    3. 在UI组件中通过this.props读取和操作状态

数据共享

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

编写Person组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import React, { Component } from 'react'

export default class Person extends Component {

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

render() {
return (
<div>
<input ref={c => this.nameNode = c} type="text" placeholder='输入名字' />&nbsp;
<input ref={c => this.ageNode = c} type="text" placeholder='输入年龄' />
<button onClick={this.addPerson}>添加</button>
<ul>
<li>ming-ling</li>
<li>ming-ling</li>
<li>ming-ling</li>
<li>ming-ling</li>
</ul>
</div>
)
}
}

Person组件的reducer与action

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* 
该文件用于创建一个为Person组件服务的reducer,reducer的本质是一个函数
reducer函数会接到两个参数,分别为:preState之前的状态、action动作对象
*/

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:
return [data, ...preState]
default:
return preState
}
}
1
2
3
4
5
6
/* 该文件专门为Person组件生成action对象 */

import { ADD_PERSON } from '../constant'

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

Person组件中:

1
2
3
4
5
6
addPerson = () => {
const name = this.nameNode.value
const age = this.ageNode.value
const personObj = {id: nanoid(), name, age}
console.log(personObj)
}

完成数据共享

store.js中使用combineReducers()对reducers进行合并,combineReducers()调用时传入的对象就是redux保存的总状态对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
该文件专门用于暴露一个store对象,整个应用只有一个store对象
*/

// 引入createStore,专门用于创建redux中最为核心的store对象
import { legacy_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
const allReducer = combineReducers({
he: countReducer,
renmen: personReducer
})

export default legacy_createStore(allReducer, applyMiddleware(thunk))

Person组件中即可取用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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.value
const age = this.ageNode.value
const personObj = {id: nanoid(), name, age}
this.props.jia(personObj)
this.nameNode.value = ''
this.ageNode.value = ''
}

render() {
return (
<div>
<h3>计数为:{this.props.count}</h3>
<h3>现在有{this.props.renshu}人</h3>
<input ref={c => this.nameNode = c} type="text" placeholder='输入名字' />&nbsp;
<input ref={c => this.ageNode = c} type="text" placeholder='输入年龄' />&nbsp;
<button onClick={this.addPerson}>添加</button>
<ul>
{
this.props.rens.map(p => {
return <li key={p.id}>{p.name}---{p.age}</li>
})
}
</ul>
</div>
)
}
}

export default connect(
state => ({rens: state.renmen, count: state.he, renshu: state.renmen.length}), // 映射状态
{jia: createAddPersonAction} // 映射操作状态的方法
)(Person)

GIF 2022-6-3 22-51-57.gif

纯函数

纯函数是一类特别的函数: 只要是同样的输入(实参),必定得到同样的输出(返回),必须遵守以下一些约束:

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

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

高阶函数

参数或返回是函数,能实现更加动态、更加可扩展的功能

  1. 定时器设置函数

  2. 数组的forEach() / map() / filter() / reduce() / find() / bind()

  3. promise

  4. react-redux中的connect函数

Redux DevTools

icon

Edge扩展下载地址

npm安装redux-devtools-extension

store.js中进行配置:export default legacy_createStore(allReducer, composeWithDevTools(applyMiddleware(thunk)))

image.png

最终完整版代码

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