我们来看一下 src/common/header 下的 index.js 代码,如下。
import React from 'react';
import {connect} from 'react-redux';
import {
HeaderWrapper,
Logo,
Nav,
NavItem,
NavSearch,
Addition,
Button,
SearchWrapper
} from './style';
import '../../statics/iconfont/iconfont.css';
import { CSSTransition } from 'react-transition-group';
import { actionCreators } from './store';
const Header = (props) => {
return (
<HeaderWrapper>
<Logo href='/'/>
<Nav>
<NavItem className='left active'>首页</NavItem>
<NavItem className='left'>下载</NavItem>
<NavItem className='right'>登录</NavItem>
<NavItem className='right'>
<span className="iconfont"></span>
</NavItem>
<SearchWrapper>
<CSSTransition
in={props.focused}
timeout={200}
classNames="slide"
>
<NavSearch
placeholder="搜索"
className={props.focused ? "focused" : ""}
onFocus={props.handleFocus}
onBlur={props.handleBlur}
></NavSearch>
</CSSTransition>
<span
className={props.focused ? "focused iconfont" : "iconfont"}
></span>
</SearchWrapper>
</Nav>
<Addition>
<Button className='writting'>
<span className="iconfont"></span>
写文章
</Button>
<Button className='reg'>注册</Button>
</Addition>
</HeaderWrapper>
)
}
const mapStateToProps = (state) => {
return {
focused: state.header.get("focused")
}
}
const mapDispatchToProps = (dispatch) => {
return {
handleFocus () {
dispatch(actionCreators.searchFocus());
},
handleBlur () {
dispatch(actionCreators.searchBlur());
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Header);
我们可以看到 在 mapStateToProps 中的代码。state.header 是一个immutable 类型的对象,使用的是get 方法获取值,而state 是js 对象,使用 . 获取值。这样不统一的形式,感觉很不开心。
接下来,我们统一一下,把 state 转变为 immutable 对象。
我们知道 state.header 是在 src/common/header/store 下的reducer 中生成的。
state ,是在 src/store 下的reducer 中生成的。src/store/reducer.js 代码如下。
import { combineReducers } from 'redux';
import { reducer as headerReducer } from '../common/header/store';
const reducer = combineReducers({
header: headerReducer
});
export default reducer;
呃,如果我们想把这个state 转变为immutable 对象,那么,我们需要依赖一个第三方模块 redux-immutable.
我们先下载这个模块: yarn add redux-immutable
下好了后。我们来修改一下 src/store/reducer.js 代码。以前我们的 combineReducers 是来自 redux,现在我们从redux-immutable 中引用它。
import { combineReducers } from 'redux-immutable';
import { reducer as headerReducer } from '../common/header/store';
const reducer = combineReducers({
header: headerReducer
});
export default reducer;
好了。然后我们就可以统一 redux 中数据的使用格式了。打开 src/common/header 下的 index.js ,修改一下下面的函数。
const mapStateToProps = (state) => {
return {
focused: state.get("header").get("focused")
}
}
Done.