zl程序教程

您现在的位置是:首页 >  工具

当前栏目

Redux源码分析之基本概念

源码 分析 基本概念 redux
2023-09-27 14:29:05 时间

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返回的是一个函数,执行该函数就会取消订阅。