Describe state with normal object. Dispatch an action to update the data of state. Use some functions to connect action with state, that is reducer.
function visibilityFilter(state = 'SHOW_ALL', action) {
if (action.type === 'SET_VISIBILITY_FILTER') {
return action.filter;
} else {
return state;
}
}
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([{ text: action.text, completed: false }]);
case 'TOGGLE_TODO':
return state.map((todo, index) =>
action.index === index ?
{ text: todo.text, completed: !todo.completed } :
todo
)
default:
return state;
}
}
Add another reducer to call the reduces above, to manage the whole state of application:
function todoApp(state = {}, action) {
return {
todos: todos(state.todos, action),
visibilityFilter: visibilityFilter(state.visibilityFilter, action)
};
}
Action is an object, and can be logged、serialized、stored.
store.dispatch({
type: 'COMPLETE_TODO',
index: 1
})
store.dispatch({
type: 'SET_VISIBILITY_FILTER',
filter: 'SHOW_COMPLETED'
})
Action is the only datasource of store. Use store.dispatch()
to deliver action into store.
Use action generate function in Redux, to return an action:
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
Reducers specify how changes to the application state are sent to the store in response to actions.
Reducer is pure function,with prev state and prev action as params, to return new state:
function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return Object.assign({}, state, {
visibilityFilter: action.filter
})
default:
return state
}
}
import { combineReducers } from 'redux'
import * as reducers from './reducers'
const todoApp = combineReducers(reducers)
import { combineReducers } from 'redux'
const todoApp = combineReducers({
visibilityFilter,
todos
})
export default todoApp
equals to :
export default function todoApp(state = {}, action) {
return {
visibilityFilter: visibilityFilter(state.visibilityFilter, action),
todos: todos(state.todos, action)
}
}
Store’ works:
getState()
to get state;dispatch(action)
to update state;subscribe(listener)
to add listener;import {
addTodo,
toggleTodo,
setVisibilityFilter,
VisibilityFilters
} from './actions'
console.log(store.getState())
const unsubscribe = store.subscribe(() =>
console.log(store.getState())
)
store.dispatch(addTodo('Learn about actions'))
store.dispatch(addTodo('Learn about reducers'))
store.dispatch(addTodo('Learn about store'))
store.dispatch(toggleTodo(0))
store.dispatch(toggleTodo(1))
store.dispatch(setVisibilityFilter(VisibilityFilters.SHOW_COMPLETED))
unsubscribe();
store.dispatch(action)