我现在正在学习 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 }
有什么提示/想法为什么会这样吗?
最佳答案
您正在添加订阅监听器之前分派(dispatch)操作。代码按顺序执行,因此当流程到达操作调度部分时,没有定义用于输出状态的订阅。
关于javascript - Redux 中的订阅 Redux 中订阅的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58991060/