Redux源码分析之基本概念
来源:互联网 发布:linux运维工程师累吗 编辑:程序博客网 时间:2024/06/05 07:42
Redux源码分析之基本概念
Redux源码分析之createStore
Redux源码分析之bindActionCreators
Redux源码分析之combineReducers
Redux源码分析之compose
Redux源码分析之applyMiddleware
redux版本 3.7.2 (注: 分析的是redux,不是React-redux, 我这里是直接引入浏览器里,所以出现的 self.Redux,不要惊奇)
借用一张图,先了解下redux的几个概念
action: 一个操作的定义,大概是这个样子, 本身是一个对象
1
2
3
4
{
type:
'add'
,
todo
}
actionCreater: 一个函数,返回结果是一个action
1
2
3
4
5
6
function
add (todo) {
return
{
type:
'add'
,
todo
}
}
reducer: 真正更新数据操作的函数,大概是这么个样子
1
2
3
4
5
6
7
8
9
10
11
// reducer
let
todoReducer = function (state = todoList, action) {
switch
(action.type) {
case
'add'
:
return
[...state, action.todo]
case
'delete'
:
return
state.filter(todo => todo.id !== action.id)
default
:
return
state
}
}
store: 只有一个。把action,state,reducer连接起来的对象。有如下方法
- dispatch:触发一个action
- subscribe : 订阅store
- getState :获得当前的state
- replaceReducer :更换reducer
- observable :暂无研究(尴尬)
我们先来一个简单的示例,直接dispatch action模式。这里大家应该都懂,不然。。。。。。
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
/* 简单示例 */
let
{ createStore } = self.Redux
//默认state
let
todoList = []
// reducer
let
todoReducer = function (state = todoList, action) {
switch
(action.type) {
case
'add'
:
return
[...state, action.todo]
case
'delete'
:
return
state.filter(todo => todo.id !== action.id)
default
:
return
state
}
}
//创建store
let
store = createStore(todoReducer)
//订阅
function subscribe1Fn() {
console.log(store.getState())
}
let
sub = store.subscribe(subscribe1Fn)
store.dispatch({
type:
'add'
,
todo: {
id: 1,
content:
'学习redux'
}
})
store.dispatch({
type:
'add'
,
todo: {
id: 2,
content:
'吃饭睡觉'
}
})
store.dispatch({
type:
'delete'
,
id: 2
})
// 取消订阅
sub()
console.log(
'取消订阅后:'
)
store.dispatch({
type:
'add'
,
todo: {
id: 3,
content:
'打游戏'
}
})
输出如下:
createStore传入reducer生成store,store就可以订阅,和派发事件了,还是比较简单的。
- subscribe 是可以取消的,subscribe返回的是一个函数,执行该函数就会取消订阅。
阅读全文
0 0
- Redux源码分析之基本概念
- Redux源码分析之基本概念
- redux源码分析
- Redux源码分析
- redux学习笔记之<combineReducers源码解析>
- redux源码
- React实战-通过ToDo源码分析Redux的数据模型设计
- redux的reateStore,combineReducers,bindActionCreators,applyMiddleware源码分析
- React实战-深入源码了解Redux用法之Connect
- React实战-深入源码了解Redux用法之Provider
- React实战-深入源码了解Redux用法之Reducers
- React实战-深入源码了解Redux用法之Middleware
- React深入源码--了解Redux用法之Provider
- hadoop学习之路(二)hadoop基本概念原理以及单词统计任务源码分析
- MapReduce 之 倒排索引 基本概念、设计思路和源码分析
- SharpDevelop源码分析 (一、序+基本概念)
- SharpDevelop源码分析 (一、序+基本概念) 收藏
- Thrift源码分析(一)-- 基本概念
- STM32——由CAN调试想到的调试过程总结
- C++之自增、自减运算符的前缀、后缀运算符区别(5)---《More Effective C++》
- ORACLE中seq$表更新频繁的分析
- 小米推送Cordova,Cordova 小米推送 ionic 小米推送
- 正则表达式匹配任意字符
- Redux源码分析之基本概念
- Java的ReentrantLock构造函数中提供了两种锁:创建公平锁和非公平锁
- MIL测试
- java中的try...catch和finally
- Android--Alertdialog对话框,设置点击其他位置不消失
- CC3200寄存器操作
- android 小米,华为,百度推送封装(QJPushService 使用)
- 【语法】sizeof和strlen
- 赖世雄音标总结