一、概述
1、redux 是什么?
(1)redux 是一个专门用于做状态管理的 JS 库 ( 不是 react 插件库 )。
(2)它可以用在 react、angular、vue等项目中, 但基本与 react 配合使用。
(3)作用:集中式管理 react 应用中多个组件共享的状态。
学习文档:
(1)英文文档:Redux - A predictable state container for JavaScript apps. | Redux
(2)中文文档:Redux中文文档
(3)github:https://github.com/reactjs/redux
2、什么情况下需要使用 redux?
(1)某个组件的状态,需要让其他组件可以随时拿到(共享)。
(2)一个组件需要改变另一个组件的状态(通信)。
(3)总体原则:能不用就不用,如果不用比较吃力才考虑使用。
3、redux 工作流程
流程说明:
(1)React Components 是组件,用于实现某种功能,呈现某种效果。
(2)Action Creators 在 redux 中派发 action 方法,action 通过 store 的 dispatch 方法派发给 Store。
(3)Store 接收 action,连同之前的 previousState,一起传递给 Reducers。
(4)Reducers 将处理后的数据返回给 Store。
(5)Store 改变自身的 state,组件可以通过 store.getState() 方法获取到 state。
餐厅例子说明:
(1)【React Components — 客人】、【Action Creators — 服务员】、
【Store — 老板】、【Reducers — 厨师】。
(2)客人来餐厅点餐,告诉服务员具体要求(什么菜系,菜名),服务员将记录下的菜单 (action) 拿给餐厅老板,老板反手交代厨师去做菜。厨师做好菜之后,将菜拿到前台老板处,老板叫号让客人过来取。
二、案例( 基于 redux )
1、纯 react 版
/* components/Count/index.jsx */
import React, { Component } from 'react'
export default class Count extends Component {
state = { count: 0 }
//加法
increment = () => {
const { value } = this.selectNumber
const { count } = this.state
this.setState({ count: count + value * 1 })
}
//减法
decrement = () => {
const { value } = this.selectNumber
const { count } = this.state
this.setState({ count: count - value * 1 })
}
//奇数再加
incrementIfOdd = () => {
const { value } = this.selectNumber
const { count } = this.state
if (count % 2 !== 0) {
this.setState({ count: count + value * 1 })
}
}
//异步加
incrementAsync = () => {
const { value } = this.selectNumber
const { count } = this.state
setTimeout(() => {
this.setState({ count: count + value * 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>
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
<button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>
<button onClick={this.incrementAsync}>异步加</button>
</div>
)
}
}
2、redux 精简版
2.1 src 代码结构
2.2 store.js
步骤: