Redux - 取消订阅侦听器如何工作?

Web*_*man 0 javascript unsubscribe redux

我是 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 is it possible ?
unsubscribe(); 
Run Code Online (Sandbox Code Playgroud)

谢谢

Sou*_*wal 5

我认为现在回答这个问题有点晚,但为了更清楚,我想提出它。要记住的关键事项是:

  1. 究竟是什么store.subscribesubscribe观看youtube选项(和铃铛图标)的演示,现在每当频道管理员上传新视频时,它会立即调用此处的听众(即订阅)并通知您,现在如果您取消订阅,您将不会收到通知。够简单!
  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());
Run Code Online (Sandbox Code Playgroud)

这将给出输出

initial state { numOfCakes: 10 }
updated state { numOfCakes: 9 }
updated state { numOfCakes: 8 }
state after unsubscribe { numOfCakes: 7 }
Run Code Online (Sandbox Code Playgroud)

所以你看,在取消订阅后,监听器不会自动调用。所以这是最后的收获

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