react之路:使用actionCreators和constants

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

使用constants

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

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命名函数替换掉最开始命名的对象。github

在功能模块下的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中使用了spa

 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 }
相关文章
相关标签/搜索