redux是个数据流,并不依赖于react,可以和任何框架结合使用
Redux 三大原则
- 整个应用的 state 被储存在一棵 object tree 中,并且这个 object tree 只存在于唯一一个 store 中
- State 是只读的,惟一改变 state 的方法就是触发 action,action 是一个用于描述已发生事件的普通对象 使用纯函数来执行修改,为了描述action如何改变state tree ,你需要编写 reducers
- 单一数据源的设计让React的组件之间的通信更加方便,同时也便于状态的统一管理
Redux
1 | let initialState = { |
React + Redux
1 | import React, { Component } from 'react'; |
bindActionCreators
[1] actionCreate
() => store.dispatch({ type: 'INCREMENT' })
如何简化这个写法
1 | function increment(){ // actionCreator action的创建函数 |
[2] bindActionCreators
1 | import { bindActionCreators } from 'redux'; |
[3] 手写 bindActionCreator
1 | // bindAcrionCreators.js |
[4] 绑定多个 bindActionCreators
1 | import { bindActionCreators } from './redux'; |
1 | // bindAcrionCreators.js |
[5] bindActionCreators 传参
1 | function bindActionCreator(actionCreator,dispatch) { |
combineReducers
[1] 用法
1 | import { combineReducers } from 'redux'; |
[2] 手写combineReducers
1 | function combindReducers(reducers){ |
react-redux
react组件和redux仓库进行自动关联的一个库
1 | // index.js |
[1] 手写connect
// react-redux/Provider.js
1 | import React from 'react'; |
// react-redux/Context
1 | import React from 'react'; |
// react-redux/connect.js
1 | import React from "react"; |
Redux中间件
中间件派发action之后,reducer之前
原理:拦截dispatch,增强dispatch
1 | // 1、缓存老的dispatch |
可以理解为面向切面编程,AOP
redux-logger
1 | // getState获取仓库状态 |
中间件的原理和koa是一样的
redux-thunk
1 | export default function ({getState, dispatch}){ |
redux-promise
1 | export default function ({getState, dispatch}){ |
compose
[拓展]
1 | let result = add3(add2(add1('ceshi'))); |
applyMiddleware
1 | // let store = createStore(reducer); |
【applyMiddleware 实现】
1 | function applyMiddleware(...middlewares){ |
redux-persist
redux数据缓存在内存中,页面一刷新就初始化了,可以使用redux-persist持久化缓存数据
1 | npm install redux-persist -D |
官网的用法 https://github.com/rt2zz/redux-persist
1 | import { persistStore, persistReducer } from 'redux-persist'; |
页面中引入
1 | import { PersistGate } from 'redux-persist/integration/react' |
redux-saga
npm install redux react-redux redux-saga -D
在 redux-saga 的世界里,Sagas 都用 Generator 函数实现。我们从 Generator 里 yield 纯 JavaScript 对象以表达 Saga 逻辑。
1 | import { createStore, applyMiddleware } from 'redux' |
派发动作都是同步的,要异步就使用saga
明天验证:yield call 不但可以调用一个返回promise的函数,还可以调用另一个saga
thunk比较
fork
表示开启了一个新的子进程去处理这个请求,
如果调用了fork则代码不会阻塞在此,而是会向下执行。
1 | // let result = yield call(login, username, password); // 这个请求是阻塞的,只有请求login方法返回之后才能执行下面的代码 |
[中文官网]https://redux-saga-in-chinese.js.org/
http://www.zhufengpeixun.cn/2020/html/63.4.redux-saga.html
参考文章:
http://www.zhufengpeixun.cn/2020/html/63.1.redux.html
http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_usages.html
http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_two_async_operations.html
http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_three_react-redux.html