18. Action和Reducer

Action和Reducer

书写action

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
handleChange(e){
// 定义一个action,给定一个action的类型,以及数据
const action = {
type: 'change_input_value',
value: e.target.value
}
// 调用dispatch,将action传递给store
store.dispatch(action)
}

handleBtnClick(){
const action = {
type:'add_todo_item'
}
store.dispatch(action)
}


handleBtnDelete(index){
const action = {
type:'delete_todo_item',
index // 相当于index:index
}
store.dispatch(action)
}

书写reducer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const defaultState = {
inputVlaue: '',
list: []
}

export default (state = defaultState, action) => {
// 匹配action type
if (action.type === 'change_input_value'){
// 将state数据进行一次深拷贝(因为reducer可以接收state,但是绝不能修改state)
const newState = JSON.parse(JSON.stringify(state));
// 改变其中inputVlaue的值为 action中的value
newState.inputVlaue = action.value
return newState;
}

if (action.type === 'add_todo_item'){
const newState = JSON.parse(JSON.stringify(state));
newState.list.push(newState.inputVlaue)
newState.inputVlaue = '';
return newState;
}

if (action.type === 'delete_todo_item'){
const newState = JSON.parse(JSON.stringify(state));
// 删除一项
newState.list.splice(action.index, 1);
return newState;
}

return state;
}

订阅并修改值

1
2
3
4
5
6
7
8
9
10
11
12
13
class TodoList extends Component{
constructor(props){
super(props);
this.state = store.getState()

// 绑定thid指向
this.handleChange = this.handleChange.bind(this);
this.handleStoreChange = this.handleStoreChange.bind(this)
this.handleBtnClick = this.handleBtnClick.bind(this)

// 订阅store,如果store有变化,就触发handleStoreChange函数
store.subscribe(this.handleStoreChange)
}
1
2
3
4
handleStoreChange(){
// 将store中的数据进行同步
this.setState(store.getState());
}

https://github.com/rexyan/simple_react/tree/Action%E5%92%8CReducer