あいつの日誌β

働きながら旅しています。

Redux.js を最速で試す

準備

mkdir practice-redux && cd $_
mkdir src www
npm init -f
npm install --save-dev webpack webpack-dev-server
npm install --save-dev babel-core babel-loader babel-preset-es2015
npm install --save-dev babel-preset-stage-0 babel-polyfill
npm install --save-dev babel-preset-react

create webpack.config.js:

const path = require('path');
const webpack = require('webpack');

module.exports = { 
  entry: [path.resolve('src/app.js')],
  output: {
    path: path.resolve('www'),
    filename: 'bundle.js',
  },  
  devtool: 'inline-source-map',
  devServer: {
    contentBase: path.resolve('www'),
    port: 3000,
    hot: false,
    inline: true,
    colors: true
  },  
  resolve: {
    extensions: ['', '.js'],
  },  
  module: {
    loaders:[
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel' },
    ]   
  }
};

create .babelrc:

{
  "presets": ["react", "es2015", "stage-0"]
}

create src/app.js

sayHello();
function sayHello(word = 'hello') {
  console.log(word);
}

implement it.

$(npm bin)/webpack && node www/bundle.js
hello

開始

install redux

npm install --save redux

update src/app.js:

import { createStore } from 'redux'

/**
 * This is a reducer, a pure function with (state, action) => state signature.
 * It describes how an action transforms the state into the next state.
 *
 * The shape of the state is up to you: it can be a primitive, an array, an object,
 * or even an Immutable.js data structure. The only important part is that you should
 * not mutate the state object, but return a new object if the state changes.
 *
 * In this example, we use a `switch` statement and strings, but you can use a helper that
 * follows a different convention (such as function maps) if it makes sense for your
 * project.
 */
function counter(state = 0, action) {
  switch (action.type) {
  case 'INCREMENT':
    return state + 1
  case 'DECREMENT':
    return state - 1
  default:
    return state
  }
}

// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
let store = createStore(counter)

// You can use subscribe() to update the UI in response to state changes.
// Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.
// However it can also be handy to persist the current state in the localStorage.

store.subscribe(() =>
  console.log(store.getState())
)

// The only way to mutate the internal state is to dispatch an action.
// The actions can be serialized, logged or stored and later replayed.
store.dispatch({ type: 'INCREMENT' })
// 1
store.dispatch({ type: 'INCREMENT' })
// 2
store.dispatch({ type: 'DECREMENT' })
// 1

implement it.

$(npm bin)/webpack && node www/bundle.js
1
2
1

続きは WEB で http://redux.js.org/