javascript - Redux 中的订阅 Redux 中订阅的奇怪行为
问题描述
我现在正在学习redux。下面共享的代码独立于 React,因此不考虑 React 集成。
下面是 redux-basics.js,它有Reducer、Store、Action 和 Subscription部分
const redux = require('redux');
const createStore = redux.createStore;
// Note : Store Creation is actually dependent on Reducer Thats why reducer must be created first.
// Reducer
const initialState = { counter : 0}
const rootReducer = (state = initialState,action) => {
if(action.type === 'INCR_COUNTER'){
return { ...state,
counter : state.counter + 1 }
}
if(action.type === 'ADD_COUNTER'){
return { ...state,
counter : state.counter + action.value }
}
return state;
}
// Store
const store = createStore(rootReducer);
console.log(store.getState())
// Subscription
store.subscribe(() => {
console.log(" SUbscription " , store.getState() );
})
// Despatching an Action
store.dispatch({type : "INCR_COUNTER"});
store.dispatch({type: "ADD_COUNTER",
value : 10
});
console.log(store.getState());
然后我得到如下输出(这是正确的!):
Ps-MBP:redux--01-start pramod$ node redux-basics.js
{ counter: 0 }
SUbscription { counter: 1 }
SUbscription { counter: 11 }
{ counter: 11 }
但是,当我将侦听器移到调度方法下方时,订阅将不起作用?我正在尝试我缺少的东西,或者为什么会这样?我正在做的代码如下:(我以为它会打印订阅方法输出,但事实并非如此)
// Despatching an Action
store.dispatch({type : "INCR_COUNTER"});
store.dispatch({type: "ADD_COUNTER",
value : 10
});
// Subscription
store.subscribe(() => {
console.log(" SUbscription " , store.getState() );
})
console.log(store.getState())
进行上述代码转换后,代码输出如下:
Pramod:redux--01-start pramod$ node redux-basics.js
{ counter: 0 }
{ counter: 11 }
任何提示/想法为什么会这样?
解决方案
您在添加订阅侦听器之前调度操作。代码是按顺序执行的,因此当流到达动作调度部分时,没有定义用于输出状态的订阅。
推荐阅读
- ios - 如何在 UICollectionViewCell 上设置约束?
- c# - 无法访问 Startup.cs 之外的 IApplicationBuilder 的所有扩展方法
- python - Python unittest:对值列表运行相同的测试,但将它们视为单独的测试
- python - 如何从 python 的列表中提取特定的电子邮件?
- php - Laravel:在刀片中显示两个日期之间的差异
- mysql - RMySQL 和 data.frame:强制引入整数范围的 NA
- c++ - 如何使用管道将字符串从孩子发送到父母
- python - 在python中递归地转置矩阵
- java - WebDriverException:未知错误:无法将窗口状态更改为最大化,当前状态对于 MacOSX 上的 ChromeDriver v2.43 和 Chrome 70 是正常的
- ruby-on-rails - 在 Rails5.2.1 中上传文件的最佳方式