Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

redux的原理是否源于闭包?

根据源码结合自己的理解写出的简单代码。
不知道redux是否是这个原理。

export default function (counter, defaultState){
  let state = defaultState || counter(undefined, {})
  let subscribe = []
  return {
    dispatch(action){
      let newState = counter(state, action)
      if (state === newState) return

      state = newState
      subscribe.forEach(fun=>fun(state))
    },
    getState(){
      return state
    },
    subscribe(fun){
      subscribe.push(fun)
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

这里确实是有闭包哦,你return出去的dispatch,getState,subscribe方法都引用了变量state,subcribe,所以就形成了闭包,这两个变量不会被回收,会一直在内存里面。我也写了reduxreact-redux的文章,给楼主参考:
手写一个Redux,深入理解其原理
手写一个React-Redux,玩转React的Context API


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...