我現(xiàn)在正在學(xué)習(xí)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());然后我得到如下輸出(這是正確的?。篜s-MBP:redux--01-start pramod$ node redux-basics.js { counter: 0 } SUbscription { counter: 1 } SUbscription { counter: 11 }{ counter: 11 }但是,當(dāng)我將偵聽器移到調(diào)度方法下方時,訂閱將不起作用?我正在嘗試我缺少的東西,或者為什么會這樣?我正在做的代碼如下:(我以為它會打印訂閱方法輸出,但事實并非如此)// 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())進行上述代碼轉(zhuǎn)換后,代碼輸出如下:Pramod:redux--01-start pramod$ node redux-basics.js { counter: 0 }{ counter: 11 }任何提示/想法為什么會這樣?
Redux 中的訂閱 Redux 中訂閱的奇怪行為
梵蒂岡之花
2022-01-07 20:46:38