我是 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();
谢谢
最佳答案
我认为现在回答这个问题有点晚了,但为了更清楚,我想提出来。
要记住的关键事项是:
store.subscribe
到底是什么,演示一下 youtubesubscribe
选项(和响铃图标),现在只要 channel 管理员上传新视频,它就会立即调用监听器(即订阅)在这里并让您收到通知,现在如果您取消订阅,您将不会收到通知。足够简单!store.subscribe
或者说只要状态因分派(dispatch)操作而更改,就会调用监听器函数。- 订阅函数的返回类型也是一个
取消订阅
更改监听器的函数。
//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 thesubscribe
function so it does not call the subscribe function again, rather call another function whichunsubscribes the change listener
.
关于javascript - Redux - 取消订阅监听器如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50892594/