react之路:使用actionCreators和constants

github仓库地址:https://github.com/wanghao12345/react-book

使用constants

constants主要是用来管理一些固定的常量,在功能模块下的store新建constants.js文件。内容如下:

1 export const SEARCH_FOCUS = 'header/SEARCH_FOCUS'
2 export const SEARCH_BLUR = 'header/SEARCH_BLUR'
3 export const SEARCH_FOCUS = 'header/SEARCH_FOCUS'
4 export const SEARCH_BLUR = 'header/SEARCH_BLUR'
5 export const SEARCH_FOCUS = 'header/SEARCH_FOCUS'
6 export const SEARCH_BLUR = 'header/SEARCH_BLUR'
7 export const SEARCH_FOCUS = 'header/SEARCH_FOCUS'
8 export const SEARCH_BLUR = 'header/SEARCH_BLUR'
9 ......

使用actionCreators

最开始在使用mapDispatchToProps的dispatch进行发送action的时候,action是我们自己命名的一个对象,现在使用actionCreators命名函数替换掉最开始命名的对象。

在功能模块下的store下新建actionCreators.js。如下:

1 import * as constants from './constants'
2 
3 export const searchFocus = () => ({
4     type: constants.SEARCH_FOCUS
5 })
6 
7 export const searchBlur = () => ({
8     type: constants.SEARCH_BLUR
9 })

然后就可以在mapDispatchToProps中使用了

 1 import { actionCreators }  from './store'
 2 /**
 3  *  将dispatch映射到props(改变state)
 4  * @param dispatch
 5  */
 6 const mapDispatchToProps = (dispatch) => {
 7     return {
 8         // 聚焦
 9         handleInputFocus () {
10             // const action = {
11             //     type: 'search_focus'
12             // }
13             // dispatch(action)
14 
15             // 使用actionCreators
16             dispatch(actionCreators.searchFocus())
17         },
18         // 离焦
19         handleInputBlur () {
20             // const action = {
21             //     type: 'search_blur'
22             // }
23             // dispatch(action)
24 
25             // 使用actionCreators
26             dispatch(actionCreators.searchBlur())
27         }
28     }
29 }