如何理解Redux中subscribe的作用

2019-01-27  本文已影响58人  亚讯

自己总结了以下redux的过程

1、使用函数createStore创建store数据点

2、创建Reducer。它要改变的组件,它获取state和action,生成新的state

3、用subscribe监听每次修改情况

4、dispatch执行,reducer(currentState,action)处理当前dispatch后的传入的action.type并返回给currentState处理后的state,通过currentListeners.forEach(v=>v())执行监听函数,并最后返回当前 action状态

但还是不理解subscribe在redux里面的作用,是观察store的变化么
export function createStore(reducer) {

let currentState = {}
let currentListeners = []

function getState() {
  return currentState
}

function subscribe(listener) {
  //传入函数
  currentListeners.push(listener)
}

function dispatch(action){
  currentState = reducer(currentState,action)
  currentListeners.forEach(v=>v())
  return action
}

//触发初始状态
dispatch({type:'@TYRMARS/Mars-Redux'})
  return {getState,subscribe,dispatch}
}

解析1:

subscribe 这个函数是用来去订阅 store 的变化,比如你每次对 store 进行 dispatch(action) 都会触发 subscribe 注册的函数调用,这个在实际情况不是必须要的,看自己的应用场景,比如你想监控 store 的全局变化时 可以用 subscript 订阅一下,然后作一些反应

解析2:

每次通过dispatch 修改数据的时候,其实只是数据发生了变化,如果不手动调用 render方法,页面上的内容是不会发生变化的。

但是每次dispatch之后都手动调用很麻烦啊,所以就使用了发布订阅模式,监听数据变化来自动渲染。

上一篇下一篇

猜你喜欢

热点阅读