REDUX
predictable state container
$(document.body).click(function () {
$('div').each(function (i) {
if (this.style.color !== 'blue') {
this.style.color = 'blue';
} else {
this.style.color = '';
}
});
});
CAN YOU SEE THE PROBLEM?
<div>
<div>
state
state
<body>
STATE
<div
ng-repeat="item in ctrl.itemList"
ng-style="{color: item.color}"
ng-click="ctrl.toggleColorOf(item)">
</div>
function ctrl() {
this.itemList = [{color: 'blue'}];
this.toggleColorOf = item =>
item.color === '' ? 'blue' : ''
}
ANGULAR TO THE RESCUE!
view
controller
service
state
state
service
state
service
state
SINGLE SOURCE OF TRUTH
PRINCIPLE OF REDUX #1
ONE STORE
ONE STORE TO RULE THEM ALL
ONE STORE TO FIND THEM
ONE STORE TO BRING THEM ALL
AND IN THE DARKNESS BIND THEM
smart component
store
state
smart component
smart component
STATE IS READ-ONLY
PRINCIPLE OF REDUX #2
MVI
Model – View – Intent
Also in this category: Cycle.js
We express an intent to mutate the state by emitting an action
{
type: 'INCREMENT',
value: 1
}
ACTION
ACTION CREATOR
export function increment(value) {
return {
type: 'INCREMENT',
value
};
}
CHANGES ARE MADE WITH PURE FUNCTIONS
PRINCIPLE OF REDUX #3
(state, action) => state
REDUCER
0
INCREMENT BY 1
1
export function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + action.value;
default:
return state
}
}
REDUCER
REDUCER
REDUCER
REDUCER
REDUCER
REDUCER
component
interacts with
action
is passed to
reducers
generate a new
state
DATA FLOW
dispatches an
updates the
import {createStore} from 'redux';
import {counter} from './reducers';
import {increment} from './actions';
const store = createStore(counter);
store.dispatch(increment(1));
store.dispatch(increment(2));
store.getState(); // 3
BASIC EXAMPLE
Redux
By Oleg Sklyanchuk
Redux
Introduction to Redux
- 430