对'create Unsubscribe() using store.subscribe() method in Redux'的困惑



我正在学习如何使用store.subscribe((方法创建Unsubscribe(。下面是代码。我不理解其中的逻辑:为什么我们使用store.subscribe方法将unsubscribe常量声明为商店的unsubscribe函数。(从字面上讲,订阅应该为商店订阅"一些东西",对吧?(

import store from './store';
const unsubscribe = store.subscribe(
() => console.log("Store changed!", store.getState())
);
store.dispatch({
type: "bugAdded",
payload: {
description: "Bug1"
}
});
unsubscribe();
store.dispatch({
type: "bugRemoved",
payload: {
id: 1
}
});

此外,请查看以下修改后的代码:即使只声明常量取消订阅,控制台仍然执行store.subscribe方法。

import store from './store';
const unsubscribe = store.subscribe(
() => console.log("Store changed!", store.getState())
);
store.dispatch({
type: "bugAdded",
payload: {
description: "Bug1"
}
});
// unsubscribe();
store.dispatch({
type: "bugRemoved",
payload: {
id: 1
}
});

上面的代码与下面的代码有相同的输出(混淆了,任何人都可以解释(

import store from './store';
store.subscribe(
() => console.log("Store changed!", store.getState())
);
store.dispatch({
type: "bugAdded",
payload: {
description: "Bug1"
}
});
store.dispatch({
type: "bugRemoved",
payload: {
id: 1
}
});

store.subscribe只会为我们的存储创建一个订阅,它会监听存储并等待它更改,每次存储更改时,它都会执行我们传递给它的回调。当我们订阅存储时,它会返回一个函数来注销订阅,我们可以随时调用它。

你可以在redux文档上阅读更多关于它的信息

最新更新