您的位置:首页 > 移动开发

[Redux] Wrapping dispatch() to Log Actions

2016-06-07 04:25 483 查看
We will learn how centralized updates in Redux let us log every state change to the console along with the action that caused it.

import { createStore } from 'redux';
import throttle from 'lodash/throttle';
import todoApp from './reducers';
import { loadState, saveState } from './localStorge';

const addLoggingToDispatch = (store) => {

const rawDispatch = store.dispatch;

// If browser not support console.group
if (!console.group) {
return rawDispatch;
}

return (action) => {
console.group(action.type);
console.log('%c prev state', 'color: gray', store.getState());
console.log('%c action', 'color: blue', action);
const returnValue = rawDispatch(action);
console.log('%c next state', 'color: green', store.getState());
console.groupEnd(action.type);
return returnValue;
};
};

const configureStore = () => {
const persistedState = loadState();
const store = createStore(todoApp, persistedState);

// If in production do not log it
if (process.env.NODE_ENV !== 'production') {
store.dispatch = addLoggingToDispatch(store);
}

store.subscribe(throttle(() => {
saveState({
todos: store.getState().todos,
});
}, 1000));

return store;
};

export default configureStore;


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: