React-Redux:从合并Reducers获取Store并在自定义中间件查看状态链
如何在Redux自定义中间件中查看完整Store状态?
你要的需求其实很容易实现——Redux给中间件传入的store参数本身就提供了getState()方法,调用它就能直接获取由所有子Reducer组合而成的完整状态树,不管是哪个Reducer负责的状态,都会包含在里面。
给你补全并修改你的自定义中间件代码,直接就能看到完整Store状态:
import {createStore, applyMiddleware, compose} from 'redux'; import rootReducer from '../reducers'; import thunk from 'redux-thunk'; import {createLogger} from 'redux-logger'; import PouchDB from 'pouchdb'; const logger = createLogger({collapsed: true}); const customMiddleware = store => next => action => { // 在action被处理前,获取当前完整的Store状态 const preActionState = store.getState(); console.log('Action处理前的完整Store状态:', preActionState); // 把action传递给下一个中间件或者Reducer const actionResult = next(action); // 在action被处理后,获取更新后的完整Store状态 const postActionState = store.getState(); console.log('Action处理后的完整Store状态:', postActionState); return actionResult; }; // 把自定义中间件加入中间件链 const store = createStore( rootReducer, compose( applyMiddleware(thunk, logger, customMiddleware) // 若需Redux DevTools支持,可添加如下配置 // window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() ) );
这里有几个关键点要说明:
store.getState()返回的就是rootReducer组合后的完整状态树——如果你用了combineReducers来组合子Reducer,状态树的结构会和你组合时定义的key完全对应,比如你有userReducer和postReducer,状态树就会是{ user: ..., post: ... }。- 你可以选择在action处理前后都打印状态,这样能清晰看到单个action对整个Store状态的影响。
- 虽然你已经用了
redux-logger,但自定义中间件里的状态打印可以更灵活——比如只针对特定类型的action打印状态,或者对状态做自定义格式化后再输出。
内容的提问来源于stack exchange,提问作者Narolan
相关产品推荐
相关产品推荐

