state
{
todos: [{
text: 'Eat food',
completed: true
}, {
text: 'Exercise',
completed: false
}],
visibilityFilter: 'SHOW_COMPLETED'
}
reducer
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
}
}
action
Actions are plain objects describeing what happened in the app, and serve as the sole way to describe an intention to mutate the data.
{ type: 'ADD_TODO', text: 'Use Redux' }
action creator
使用函数来创建 action。
export function addTodo(text) {
return {
type: 'ADD_TODO',
text
}
}
dispatch(addTodo('Use Redux'))
function makeActionCreator(type, ...argNames) {
return function (...args) {
const action = { type }
argNames.forEach((arg, index) => {
action[argNames[index]] = args[index]
})
return action
}
}