Redux - 取消订阅听众的工作原理?

时间:2018-06-16 23:48:33

标签: javascript redux unsubscribe

我是Redux的新手。 我想知道为什么从根本上取消订阅听众以及它是如何运作的? 我知道register函数返回一个取消订阅,但在下面的例子中,当我们调用unsubscribe方法时为什么它不只是重新触发嵌套在变量中的函数?我们可以看到:

let unsubscribe = store.subscribe(() => {  
    // let unsubscribe nests a function   
    // execute every time the state changes
    const state = store.getState(); 
});
// but here instead of call the nested function it cancels the listener, how it is possible ?
unsubscribe(); 

由于

3 个答案:

答案 0 :(得分:2)

我认为回答这个问题有点晚了,但是更明确地说,我想提出这个问题。 要记住的关键是:

  1. 确切是store.subscribe是什么,请观看youtube subscribe选项(和响铃图标)的演示,现在每当频道管理员上传新视频时,它都会立即在此处调用监听器(即订阅)并获取您已收到通知,现在,如果您取消订阅,则不会收到通知。很简单!
  2. store.subscribe或说由于分派的操作而在状态改变时调用监听器函数。
  3. 订阅函数的返回类型还是unsubscribes更改侦听器的函数。

//Action is an object with type property
const BUY_CAKE = 'BUY_CAKE'; 

// Action creator is a function that returns an actions 
function buyCake() {
  return {
    type: BUY_CAKE,
    info: 'first redux action',
  }
}

// initial state for reducer, Reducer -> (previousstate, action) =>newState
const initialState = {
  numOfCakes: 10
}

// This is our reducer function 
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case BUY_CAKE: return {
      ...state,  // making the copy of state object
      numOfCakes: state.numOfCakes - 1
    }
    default: return state;
  }
}

const store = createStore(reducer);
console.log("initial state", store.getState());
/*Returns the current state tree of your application. It is equal to the last value returned by the store's reducer.*/

// The subscribe listerner will be called eveytime an action is dispatched
const unsubscribe = store.subscribe(() => console.log("updated state", store.getState()))
store.dispatch(buyCake());
store.dispatch(buyCake());
unsubscribe();
store.dispatch(buyCake());
console.log("state after unsubscribe", store.getState());

这将给出输出

initial state { numOfCakes: 10 }
updated state { numOfCakes: 9 }
updated state { numOfCakes: 8 }
state after unsubscribe { numOfCakes: 7 }

因此您看到,取消订阅后,不会自动调用该侦听器。这是最后的收获

当您调用unsubscribe时,它是一个从subscribe函数返回的函数,因此它不会再次调用subscription函数,而是调用另一个unsubscribes the change listener函数。 / p>

答案 1 :(得分:1)

redux中的unsubscribe函数实际上是在redux createStore方法中的subscription方法内部实现的。运作方式如下:

//Inside store
    const subscribe = (listener) => {
           listeners.push(listener);
           return () => {
           listeners.filter(l => l !== listener);
        };
        };
// End of inside store 

const unsubscribe = store.subscribe(handleChange)
unsubscribe()

答案 2 :(得分:0)

我们正在调用store.subscribe()并将其传递给回调函数。每当商店更改时,都会调用该回调。

函数签名说明,subscription期望在每次分派时都会调用该函数,并返回一个函数,该函数在调用时将取消订阅侦听器。像这样想象:

function store.subscribe(callback){ 
    //execute the callback function
    callback();
    return store.unsubscribe()
}