Redux = Reducer + Flux
Flux 的缺点:
公共存储区域 store 可以有很多个, 这样会出现数据依赖的现象
Redux 的工作流程:
Store : (图书馆的管理员, 管理图书) 存储数据的公共区域. 存储了所有数据, 每个组件从 store 里拿数据, 每个组件也要去 store 里改数据.
React Components: 组件
Action Creators: (说的要借什么书的这句话)
Reducers: (记录本)
- 安装 redux
- 创建 store 文件夹, 新建 index.js
- import { createStore } from ‘redux’
- 调用该方法创建 store
- ------------以上相当于创建了 store
- 然后现在只有管理员, 还需要记录的小本也就是 reducer
- 在 store 文件夹中新建 reducer.js
- 里面放state 数据, 并暴露出去, 在store 里引入, 把 reducer 传给 store. const store = createStore(reducer)
- ------------以上相当于让 store 里有数据了
- 现在该连接组件了
- TodoList.js 里 import store from ‘./store’
- store.getStore 方法取数据
以上已经完成了创建 store 和 reducer, 并可以在组件中取到 state 数据
下面开始让组件可以改变 state 数据
- 创建 action
action 是个对象的形式
const action = {
type: 'change_input_value', //创建一句话
value: e.target.value, //这句话传什么
}
- 把这句话传给 store
store 提供了一个方法 dispatch, 调用这个方法传
- 现在已经传了, 但是 store 不知道该怎么处理. 因此他要去查 reducer 手册.
怎么查呢?
要把当前 store 里的数据(previousState) 和 action 一起转发传给 reducer 去查. 这一步 store 自动去做
reducer 拿到当前数据和 action 之后, 告诉 store 怎么做
再来一次
- 绑定事件
- 对事件方法作用域进行绑定
- 实现这个方法
- 当 btn 点击的时候, 希望 store 数据发生改变, 如果想改变数据先创建一个 action, action 长得就像一个对象, 里面必须有 type 字段, 用来告诉 store 干甚么.
- action 有了然后把它发给 store, 怎么发. 用store.dispatch(action)
- 传给了 store, 但是 store 不知道该怎么做, store 就把之前 store 里的数据和 action 传给 reducer. reducer 来处理, 然后把处理好的结果返回给 store
- 在 reducer 中, 会接收到之前 store 里的数据和 action, 计算好后 return newState
- store 接收返回的数据, 就把当前 store 里的数据替换成 reducer 返回的新数据. store 里的数据就发生了变化
- 之前在组件里监听了 store 数据的变化. store.subscribe(this.handleStoreChange) . 这时重新从 store 里取数据, 替换掉当前组件里的数据
- 基本实现了功能
总结吧:
要改变 store 里的数据先要去派发 action, action 通过 dispatch 方法传递给 store, store 再把当前 store 里的数据和 action 转发给 reducer, reducer 是一个函数, 它接收到 state 和 action 之后, 做一些处理, 返回新的 state 给 store. store 用新的 state 替换掉之前的 store 里的数据, 然后 store 数据发生改变的时候, react 组件会感知到 store 发生改变, 这时从 store 里重新取数据更新组件内容, 页面就跟着发生变化
Redux设计和使用的三大原则
store 必须唯一: 整个应用之中只有一个 store
只有 store 能够改变自己的内容
reducer 必须是纯函数(纯函数:给定固定的输入, 就一定会有固定的输出, 而且不会有任何副作用 , 一旦一个函数里面有 setTimeout 或者 ajax 请求或者与日期相关的时候, 就不再是纯函数, 所以 reducer 里面不能有异步操作, 也不能有跟时间相关的操作.. reducer 里面也不能有副作用(对参数的修改就是副作用))
Redux 的核心 api
createStore: 创建一个 store
store.dispatch: 派发 action, action 传递给 store
store.getState: 帮助我们获取 store 里面所有的数据内容
store.subscribe: 订阅 store 的改变, 只要 store 发生改变, store.subscribe 这个函数接收的回调函数就会被执行.