react之路:使用immutable管理store中的数据

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

简介

immutable能够将store中的数据封装成一个immutable对象,这个对象拥有get,set等方法,这样就能够经过这些方法对store中的数据进行管理git

使用

1.安装immutable依赖

npm install immutable --save 或者  yarn add immutablegithub

2.store中引入

import { fromJS } from 'immutable'npm

3.使用get方法

在mapStateToProps中获取state数据时:spa

 1 /**
 2  * 将仓库的state映射到props(获取state)
 3  * @param state
 4  */
 5 const mapStateToProps = (state) => {
 6     return {
 7         // 没有使用immutable
 8         // focused: state.header.focused
 9         // 使用了immutable
10         focused: state.header.get('focused')
11     }
12 }

4.使用set方法

 1 import * as constants from './constants'
 2 
 3 import { fromJS } from 'immutable'
 4 
 5 // fromJS将一个js对象转化成immutable对象
 6 const defaultState = fromJS({
 7     focused: false
 8 })
 9 
10 export default (state = defaultState, action) => {
11 
12     if (action.type === constants.SEARCH_FOCUS) {
13         // 没有使用immutable
14         // return {
15         //     focused: true
16         // }
17 
18         // 使用了immutable
19         // immutable对象的set方法,会结合以前的immutable对象的值
20         // 和设置的值,返回一个全新的对象
21         return state.set('focused', true)
22     }
23 
24     if (action.type === constants.SEARCH_BLUR) {
25         // 没有使用immutable
26         // return {
27         //     focused: false
28         // }
29 
30         // 使用了immutable
31         return state.set('focused', false)
32     }
33 
34     return state
35 }
相关文章
相关标签/搜索