Introduction
Motivation
http://redux.js.org/docs/introduction/Motivation.html
Mutation & Asynchronicity
Solving by imposing certain restrictions -- Principles
Principles
http://redux.js.org/docs/introduction/ThreePrinciples.html
Single source of truth
The state of your whole application is stored in an object tree within asingle store
State is read-only
the only way to mutate the state is to emit an action, an objectdescribe what happened
Changes are made with pure functions
to specify how the state tree is transformed by actions, you write purereducers
Basics
Actions
http://redux.js.org/docs/basics/Actions.html
http://redux.js.org/docs/recipes/ReducingBoilerplate.html
actions are payloads of information that send data from your application to your store.
define action type:
const ADD_TODO = 'ADD_TODO';
action object:
{
type: ADD_TODO,
payload: {
text: "this is todo text"
}
}
action creators:
action creators are exactly that -- functions that create actions
function addTodo(text) {
return {
type: ADD_TODO,
payload: {
text: text
}
};
}
async actions
Reducers
Actions describe something happened, but don't specify how the application's state changes in response. This is the job of a reducer.
design the state shape
{ todos: [ ... ], .... }
handling actions
(previousState, action) => newState
initialState = { todos: [] };
function todoApp (state = initialState, action) {
switch (action.type) {
case ADD_TODO:
return Object.assign({}, state, {
todos: [
...state.todos,
{
text: action.payload.text
}
]
});
default:
return state;
}
}
split reducers / handle more actions
Store
http://redux.js.org/docs/basics/Store.html
responsibilities:
1. holds application state (from reducer)
2. allows access state via store.getState()
3. allows state to be updated via store.dispatch(action)
4. store.subscribe(listener)
5. unsubscribe
import { createStore } from 'redux'
import todoApp from './reducers'
let store = createStore(todoApp)
let unsubscribe = store.subscribe(() => console.log('state changed'));
unsubscribe();
Data Flow
Advanced
Async Actions
ajax call