2020/11/22、 周日、今天又是奋斗的一天。 |
@Author:Runsen
你是否将所有 JavaScript 脚本放在一个大文件中,并在所有页面上使用这个文件?如果是这样,你可能需要考虑使用代码拆分!
代码拆分
我们将变量的类型拆分到constants.js
constants.js
export const SERACH_FOCUS = 'header/SERACH_FOCUS'
export const SERACH_BLUR = 'header/SERACH_BLUR'
注意所有的变量类型都必须要export 导出。
actionCreators 本身是一个函数,同样需要export出来。主要用在mapDispathToProps中的dispatch。
actionCreators.js
import * as constants from './constants'
export const searchFocus = () =>({
type: constants.SERACH_FOCUS
})
export const searchBlur = () =>({
type: constants.SERACH_BLUR
})
上面就完成了对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. 性能好 (通过字典树对数据结构的共享)
安装: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;
}
store的数据储存是来自header/store/reducer.js