代码见https://gitee.com/XiaoKunErGe/JianShu.git历史版本第9、10次提交
immutable库是facebook研发的,可以帮助我们生成一个immutable对象,这个对象不可变更
1.安装immutable
打开GitHub搜索immutable 点开### immutable-js / immutable -js
yarn add immutable
2.在header的reducer中引入immutable
import { fromJS } from 'immutable';
//immutable提供了一个fromJS方法把一个JS对象转化为immutable对象
设置默认值的方法改写成
const defaultState = fromJS({
focused: false
});
3.将header的index中代码改写为如下格式
const mapStateToProps= (state)=>{
return{
// focused:state.header.focused
//这时state.header对应的数据已经是immutable数据了,所以点调用focused就不合适了
focused: state.header.get('focused')
}
}
同样header中代码改写格式如下
export default (state = defaultState, action) => {
if(action.type === constants.SEARCH_FOCUS){
// return{
// focused: true
// }
//immutable对象的set方法,会结合之前immutable对象的值和设置的值,返回一个全新的对象
return state.set('focused', true);
}
if(action.type === constants.SEARCH_BLUR){
return state.set('focused', false);
}
return state;
};
规范写法
const mapStateToProps= (state)=>{
return{
focused: state.header.get('focused')
}
}
这里state的值是最外层store中reducer里创建的,这时我们需要依赖一个第三方的模块儿叫做redux-immutable
yarn add redux-immutable
现在我们让combineReducers从redux-immutable中引用
import { combineReducers } from 'redux-immutable';
这时reducer里面的数据内容就是一个immutable类型的数据内容了
//redux提供的combineReducers可以把小的reducer合并起来
import {reducer as headerReducer} from '../commen/header/store';
//as是ES6的一个语法 这里是给reducer起一个别名headerReducer
const reducer = combineReducers({
header: headerReducer
});
export default reducer;
这时会报错
屏幕快照 2019-06-11 10.19.29.png
是因为这时这里接收的state已经是immutable对象了,这种写法就不可以了所以改写如下
const mapStateToProps= (state)=>{
return{
focused: state.get('header').get('focused')
}
immutable中还有getIn方法和上面方法是等价的
const mapStateToProps= (state)=>{
return{
focused: state.getIn(['header', 'focused'])
}
网友评论