八十五、store数据,actionCreators 与 constants 的拆分和redux-immutable的使用

网友投稿 561 2022-05-30

@Author:Runsen

你是否将所有 JavaScript 脚本放在一个大文件中,并在所有页面上使用这个文件?如果是这样,你可能需要考虑使用代码拆分!

代码拆分

我们将变量的类型拆分到constants.js

constants.js

export const SERACH_FOCUS = 'header/SERACH_FOCUS' export const SERACH_BLUR = 'header/SERACH_BLUR'

1

2

注意所有的变量类型都必须要export 导出。

actionCreators 本身是一个函数,同样需要export出来。主要用在mapDispathToProps中的dispatch。

八十五、store数据,actionCreators 与 constants 的拆分和redux-immutable的使用

actionCreators.js

import * as constants from './constants' export const searchFocus = () =>({ type: constants.SERACH_FOCUS }) export const searchBlur = () =>({ type: constants.SERACH_BLUR })

1

2

3

4

5

6

7

8

9

上面就完成了对actionCreators 与 constants 的拆分。

由于header/index.js需要导入reducer,constants,actionCreators

因此,需要在Store中的index.js将reducer,constants,actionCreators导出。

redux-immutable

在header的reducer.js里把header变成immutable对象之后,在组件里获取focused属性就得这样获取:focused:state.header.get('focused')

immutable好处。

1. 保证不可变(每次通过Immutable.js操作的对象都会返回一个新的对象) 2. 丰富的API 3. 性能好 (通过字典树对数据结构的共享)

1

2

3

4

安装:npm install redux-immutable --save

主要使用的是fromJS

import * as constants from './constants' import {fromJS} from 'immutable' const defaultState = fromJS({ focused: false }); export default (state = defaultState, action) => { if (action.type === constants.SERACH_FOCUS) { return state.set('focused',true) } if (action.type === constants.SERACH_BLUR) { return state.set('focused',false) } return state; }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

store的数据储存是来自header/store/reducer.js

JavaScript Redux

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:innodb_locks_unsafe_for_binlog和间隙锁机制
下一篇:Python3连接PostgreSQL(10.5)数据库
相关文章