LoginSignup
23

More than 5 years have passed since last update.

Reduxでアクションをデバッグする

Last updated at Posted at 2015-07-14

Developer_Tools_-_http___192_168_0_77_signup.png

追記: 最近は、redux-logger という便利なnpmモジュールがあるので、そちらを使ったほうが楽で綺麗な出力が得られます!

Redux 1.0.0-alphaからミドルウェア機構が追加されたので、アクションをデバッグするミドルウェアを追加してみる。これがあるといちいちアプリ側のコードでconsole.logしなくてもよくなるので便利。

ミドルウェアのコード

const debug = function actionDebugMiddleware() {
  return next => action => {
    console.info(action.type, action);
    next(action);
  };
};

app.js

import React from "react";
import BrowserHistory from "react-router/lib/BrowserHistory";

import {Router} from "react-router";
import {createStore, combineReducers, applyMiddleware} from "redux";
import {Provider} from "react-redux";

import routes from "routes";
import * as reducers from "reducers";

import thunk from "redux-thunk";

const reducer = combineReducers(reducers);

// ミドルウェアの宣言
const debug = function actionDebugMiddleware() {
  return next => action => {
    console.info(action.type, action);
    next(action);
  };
};

// applyMiddlewareに指定
const finalCreateStore = applyMiddleware(thunk, debug)(createStore);
const store = finalCreateStore(reducer);
const history = new BrowserHistory();

React.render(
  <Provider store={store}>
    {() => <Router history={history} children={routes}/> }
  </Provider>,
  document.getElementById("app")
);

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23