19. 拆分ActionTypes

拆分ActionTypes

新建actionTypes.js文件

1
2
3
export const CHANGE_INPUT_VALUE = 'change_input_value'
export const ADD_TODO_ITEM = 'add_todo_item'
export const DELETE_TODO_ITEM = 'delete_todo_item'

使用

1
import { CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM } from './actionTypes'
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

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;
}

https://github.com/rexyan/simple_react/tree/%E6%8B%86%E5%88%86ActionTypes