首页 > 代码库 > Redux 理解

Redux 理解

1: state 就像 model

{
    todos: [{
        text: ‘Eat food‘,
        completed: true
    }, {
        text: ‘Exercise‘,
        completed: false
    }],
    visibilityFilter: ‘SHOW_COMPLETED‘
}

 

2: action, 普通的 javascript 对象, 用来描述发生了什么

{ type: ‘ADD_TODO‘, text: ‘Go to swimming pool‘ }
{ type: ‘TOGGLE_TODO‘, index: 1 }
{ type: ‘SET_VISIBILITY_FILTER‘, filter: ‘SHOW_ALL‘ }

 

3. 为了把 action 和 state 串起来, 就是 reducer, 例如下面:

function todos(state = [], action) {
    switch (action.type) {
        case ‘ADD_TODO‘:
            return state.concat([{ text: action.text, completed: false }]);
        default:
            return state;
    }
}

 

Redux 理解