我们先来看一下 src/common/header/store 下的reducer ,如下。
import { SEARCH_FOCUS, SEARCH_BLUR } from './actionTypes';
const defaultState = {
focused: false
};
export default (state = defaultState, action) => {
if (action.type === SEARCH_FOCUS) {
let newState = JSON.parse(JSON.stringify(state));
newState.focused = true;
return newState;
}
if (action.type === SEARCH_BLUR) {
let newState = JSON.parse(JSON.stringify(state));
newState.focused = false;
return newState;
}
return state;
}
我们知道,在reducer 函数中,state 是不能修改的。但是,有时候不注意可能就把它的内容改了。总之,immutable.js 就是一个保证属性不变的第三方库。它能帮我们生成一个 immutable 对象(不可改变的)。我们将state 定义为 immutable 对象,那么state 对象如果被修改就会报错了。
github 上 immutable 的网址: https://github.com/immutable-js/immutable-js
我们先下载安装 yarn add immutable
下载好了后,我们就可以来将 state 变为immutable 对象。
打开src/common/header/store 下的reducer
import { SEARCH_FOCUS, SEARCH_BLUR } from './actionTypes';
import { fromJS } from 'immutable';
const defaultState = fromJS({
focused: false
});
export default (state = defaultState, action) => {
if (action.type === SEARCH_FOCUS) {
return state.set("focused", true);
}
if (action.type === SEARCH_BLUR) {
return state.set("focused", false);
}
return state;
}
然后,修改一下 Header 组件代码,如下。
const mapStateToProps = (state) => {
return {
focused: state.header.get("focused")
}
}
const mapDispatchToProps = (dispatch) => {
return {
handleFocus () {
dispatch(actionCreators.searchFocus());
},
handleBlur () {
dispatch(actionCreators.searchBlur());
}
}
}
Done.