Redux
Redux理解
- redux是一个专门用于做状态管理的JS库(不是react插件库)。
- 可以用在React, Angular, Vue等项目中, 但基本与React配合使用。
- 作用: 集中式管理React应用中多个组件共享的状态。
- Redux只负责管理状态
文档
英文文档 中文文档 Github
需要使用Redux的情况
- 某个组件的状态,需要让其他组件可以随时拿到(共享)。
- 一个组件需要改变另一个组件的状态(通信)。
- 总体原则:能不用就不用, 如果不用比较吃力才考虑使用。
redux工作流程
求和案例
纯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> <button onClick={this.increment}>+</button> <button onClick={this.decrement}>-</button> <button onClick={this.incrementIfOdd}>add if odd</button> <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
|
import { legacy_createStore } from 'redux'
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
|
const initState = 0 export default function countReducer(preState=initState, action) { const { type, data } = action 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'
import store from '../../redux/store'
export default class Count extends Component {
state = {}
componentDidMount() { store.subscribe(() => { this.setState({}) }) }
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> <button onClick={this.increment}>+</button> <button onClick={this.decrement}>-</button> <button onClick={this.incrementIfOdd}>add if odd</button> <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
|
export const INCREMENT = 'increment' export const DECREMENT = 'decrement'
|
新增文件xx_action.js
,创建action对象
1 2 3 4 5 6 7
|
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
|
import { legacy_createStore, applyMiddleware } from 'redux'
import countReducer from './count_reducer'
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
|
import { INCREMENT, DECREMENT } from "./constant"
export const createIncrementAction = data => ({type: INCREMENT, data})
export const createDecrementAction = data => ({type: DECREMENT, data})
export const createIncrementAsyncAction = (data, time) => { return (dispatch) => { setTimeout(() => { dispatch(createIncrementAction(data)) }, time) } }
|
React-Redux
将React组件与Redux尽可能地剥离,让UI组件与容器组件间通过props传递,便于项目后期的更新与维护
连接容器组件与UI组件
Count组件删除所有与redux有关的内容,作为UI组件
建立containers
文件夹,存放Count的容器组件,基础代码如下:
1 2 3 4 5 6 7 8
| import CountUI from '../../components/Count'
import { connect } from 'react-redux'
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> ) } }
|
求和案例
容器组件:
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
| import CountUI from '../../components/Count'
import { connect } from 'react-redux'
import { createDecrementAction, createIncrementAction, createIncrementAsyncAction } from '../../../src/redux/count_action'
function mapStateToProps(state) { return {count: state} }
function mapDispatchToProps(dispatch) { return { increment: data => dispatch(createIncrementAction(data)), decrement: data => dispatch(createDecrementAction(data)), incrementAsync: (data, time) => dispatch(createIncrementAsyncAction(data, time)) } }
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 = {}
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> <button onClick={this.increment}>+</button> <button onClick={this.decrement}>-</button> <button onClick={this.incrementIfOdd}>add if odd</button> <button onClick={this.incrementAsync}>add async</button> </> ) } }
|
- 明确两个概念:
- UI组件:不能使用任何redux的api,只负责页面的呈现、交互等
- 容器组件:负责和redux通信,将结果交给UI组件
- 如何创建一个容器组件——靠
react-redux
的connect
函数
connect(mapStateToProps, mapDispatchToProps)(UI组件)
mapStateToProps
: 映射状态,返回值是一个对象
mapDispatchToProps
: 映射操作状态的方法,返回值是一个对象
- 容器组件中的store是靠props传进去的,而不是在容器组件中直接引入
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}),
{ 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
| import { connect } from 'react-redux'
import { createDecrementAction, createIncrementAction, createIncrementAsyncAction } from '../../../src/redux/count_action' import React, { Component } from 'react'
class Count extends Component {
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> <button onClick={this.increment}>+</button> <button onClick={this.decrement}>-</button> <button onClick={this.incrementIfOdd}>add if odd</button> <button onClick={this.incrementAsync}>add async</button> </> ) } }
export default connect( state => ({count: state}), { increment: createIncrementAction, decrement: createDecrementAction, incrementAsync: createIncrementAsyncAction } )(Count)
|
优化总结
-
容器组件和UI组件整合成一个文件
-
无需自己给容器组件传递store,给<App/>
包裹一个<Provider store={store}></Provider>
即可
-
使用了react-redux后不需要再自己检测redux中状态的改变,容器组件可以自动完成这个工作
-
mapDispatchToProps
也可以简单的写成一个对象
-
一个组件要和redux“打交道”要经过哪几步?
-
定义好UI组件—不暴露
-
引入connect
生成一个容器组件,并暴露,写法如下:
1 2 3 4
| connect( state => ({key:state}), {key:xxxxxAction} )(UI组件)
|
-
在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='输入名字' /> <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
|
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
|
import { ADD_PERSON } from '../constant'
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
|
import { legacy_createStore, applyMiddleware, combineReducers } from 'redux'
import countReducer from './reducers/count'
import personReducer from './reducers/person'
import thunk from 'redux-thunk'
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='输入名字' /> <input ref={c => this.ageNode = c} type="text" placeholder='输入年龄' /> <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)
|
纯函数
纯函数是一类特别的函数: 只要是同样的输入(实参),必定得到同样的输出(返回),必须遵守以下一些约束:
- 不得改写参数数据
- 不会产生任何副作用,例如网络请求,输入和输出设备
- 不能调用
Date.now()
或者Math.random()
等不纯的方法
redux的reducer函数必须是一个纯函数
高阶函数
参数或返回是函数,能实现更加动态、更加可扩展的功能
-
定时器设置函数
-
数组的forEach()
/ map()
/ filter()
/ reduce()
/ find()
/ bind()
-
promise
-
react-redux中的connect
函数
Redux DevTools
Edge扩展下载地址
npm安装redux-devtools-extension
store.js
中进行配置:export default legacy_createStore(allReducer, composeWithDevTools(applyMiddleware(thunk)))
最终完整版代码
- 所有变量命名要规范,尽可能触发对象的简写形式
reducers
文件夹中编写index.js
专门用于汇总并暴露所有的reducer