我现在正在学习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.// Reducerconst 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())// Subscriptionstore.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});// Subscriptionstore.subscribe(() => { console.log(" SUbscription " , store.getState() );})console.log(store.getState())进行上述代码转换后,代码输出如下:Pramod:redux--01-start pramod$ node redux-basics.js { counter: 0 }{ counter: 11 }任何提示/想法为什么会这样?
添加回答
举报
0/150
提交
取消