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

标签 javascript redux unsubscribe

我是 Redux 新手。 我想知道取消订阅监听器本质上是什么以及它是如何工作的? 我知道 register 函数返回一个取消订阅,但在下面的示例中,当我们调用取消订阅方法时,为什么它不只是触发嵌套在变量内的新函数?正如我们所看到的:

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(); 

谢谢

最佳答案

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

  1. store.subscribe 到底是什么,演示一下 youtube subscribe 选项(和响铃图标),现在只要 channel 管理员上传新视频,它就会立即调用监听器(即订阅)在这里并让您收到通知,现在如果您取消订阅,您将不会收到通知。足够简单!
  2. store.subscribe 或者说只要状态因分派(dispatch)操作而更改,就会调用监听器函数。
  3. 订阅函数的返回类型也是一个取消订阅更改监听器的函数。

//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 }

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

As you call the unsubscribe, it is a function which is returned from the subscribe function so it does not call the subscribe function again, rather call another function which unsubscribes the change listener.

关于javascript - Redux - 取消订阅监听器如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50892594/

相关文章:

reactjs - useSelector 在初始页面加载时未接收状态,破坏了 Material ui 表

redux - 使用 Predicate 选项过滤 redux-logger 中的 redux-form 操作

node.js - react : Set up a large number of routes and have GET request render correctly on web server

Angular RxJS Observable : takeUntil vs.取消订阅

Javascript - 如何在末尾添加百分比符号[无jquery]

javascript - 使用 Freedom js 自动发现邻居

javascript - 使用 $(parent.window).height()

javascript - 为什么我的图像不断覆盖自身而不是在 for 循环中显示每个图像?

android - this.Touch - 多次触发事件,不知道如何取消订阅

c# - 我应该取消订阅事件吗?