本文共 1783 字,大约阅读时间需要 5 分钟。
redux版本 3.7.2 (注: 分析的是redux,不是react-redux, 我这里是直接引入浏览器里,所以出现的 self.Redux,不要惊奇)
借用一张图,先了解下redux的几个概念
action: 一个操作的定义,大概是这个样子, 本身是一个对象
{ type:'add', todo }
actionCreater: 一个函数,返回结果是一个action
function add (todo) { return { type: 'add', todo } }
reducer: 真正更新数据操作的函数,大概是这么个样子
// reducerlet 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模式。这里大家应该都懂,不然。。。。。。
/* 简单示例 */let { createStore } = self.Redux//默认statelet todoList = []// reducerlet 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 }}//创建storelet 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就可以订阅,和派发事件了,还是比较简单的。
下一篇,我们来一起分析 createStore方法。
转载地址:http://ebsel.baihongyu.com/