20. actionCreator统一创建action

actionCreator统一创建action

创建actionCreator文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM } from './actionTypes'

// 将之前的action抽取在actionCreator.js文件中,返回一个对象
export const getChangeAction = (value) => ({
type: CHANGE_INPUT_VALUE,
value
});

export const getBtnClickAction = () => ({
type: ADD_TODO_ITEM
});

export const getBtnDeleteAction = (index) => ({
type: DELETE_TODO_ITEM,
index
});

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
handleChange(e){
const value = e.target.value
const action = getChangeAction(value) // 从actionCreator中获取返回的action对象
store.dispatch(action)
}

handleBtnClick(){
const action = getBtnClickAction()
store.dispatch(action)
}

handleBtnDelete(index){
const action = getBtnDeleteAction(index)
store.dispatch(action)
}

handleStoreChange(){
this.setState(store.getState());
}

https://github.com/rexyan/simple_react/tree/actionCreator%E7%BB%9F%E4%B8%80%E5%88%9B%E5%BB%BAaction