Comenzando con redux

Instalación o configuración

Instalación básica:

Puede descargar el archivo javascript redux, usando este enlace.

También puedes instalar redux, usando bower :

bower install https://npmcdn.com/[email protected]/dist/redux.min.js

A continuación, debe incluir redux en su página:

<html>
  <head>
    <script type="text/javascript" src="/path/to/redux.min.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script>
      // Redux is available as `window.Redux` variable.
    </script>
  </body>
</html>

Instalación Npm:

Si está utilizando npm, para instalar redux, debe ejecutar:

npm install redux --save

A continuación, para usar redux, debe solicitarlo (suponiendo que esté usando un paquete de módulos, como webpack):

var redux = require('redux');

O si está utilizando transpiler es6, como babel:

import redux from 'redux';

Ejemplo de Vanilla Redux (sin React u otros)

Puede ver la demostración en ejecución haciendo clic aquí.

HTML:

<p>
  <span>Counter State</span><br />
  (<em>Will increase each minute</em>):
  <p>
    <span id="counter-state" style="font-weight: bolder"></span>
  </p>
</p>

<p>
  <button id="increment-action">+ Increase +</button>
  <button id="decrement-action">- Decrease -</button>
</p>

LÓGICA DE REDUCCIÓN:

// ------------------------ reducer helpers ------------------------
let reducers = {}

let addReducer = (reducers, actionType, reducer) =>
  reducers[actionType] = (state, action) => {
    if (action.type == actionType) {
      return reducer(state, action)
    }
  }

let reducer = (state, action) => {
  if (reducers[action.type]) {
    return reducers[action.type](state, action)
  }
  return state
}


// ------------------------ redux setup ------------------------

const { 
  createStore,
  applyMiddleware
  } = Redux


// apply logging middleware (not necessary)
// open the console to see the action logger output on each time new action dispatched
const actionLogger = ({ dispatch, getState }) => next => action => {
  console.log("action logger: action.type=%s state=%d", action.type, getState())
  return next(action)
}


// ------------------------ reducers ------------------------
// those will be creating new states and returning it,
// depending on the dispatched actions
addReducer(reducers, 'INCREMENT', (state, action) => ++state)
addReducer(reducers, 'DECREMENT', (state, action) => --state)


const DEFAULT_STATE = 0

const store = createStore(
  reducer, 
  DEFAULT_STATE, 
  applyMiddleware(actionLogger)
);


console.log(createStore)


// ------------------------ rendering ------------------------
let render = () => document.getElementById('counter-state').innerHTML = store.getState()

//
// IMPORTANT BINDING:
//
// store will be dispatching the new state to the render method each time the state changes
//
store.subscribe(render)

//
// render with the state for the first time
//
render()



// ------------------------ redux actions ------------------------

// continously increment the counter (the state) each second
setInterval(() => store.dispatch({type: 'INCREMENT'}), 1000)

// only increment the counter on click to the increase button
document
  .getElementById('increment-action')
  .addEventListener('click', () => store.dispatch({type: 'INCREMENT'}))

// only decrement the counter on click to the decrease button
document
  .getElementById('decrement-action')
  .addEventListener('click', () => store.dispatch({type: 'DECREMENT'}))