react-redux 主要是让我们更好的在react中使用redux
react-redux提供两个模块 Provider和connect
Provider
provider 这个模块是作为整个app的容器,在你原有的app Container的基础上在包上一层,它的工作很简单,就是接受redux的store作为props,并将其声明为context的属性之一,子组件可以在声明了contextTypes之后可以方便的通过this.context.store访问到store。不过我们的组件通常不需要这么做,将store放在context里,是为了给下面的connect用的。。
render(
<Provider store = {store}>
<Route/>
</Provider>
,document.getElementById('container')
);
connect
这个模块是真正意义上的链接Redux和React
Redux的运行: 首先store中维护了一个state,我们dispatch一个action,接下来reducer根据这个action更新state。。
映射到我们的react应用中,store中维护的state就是我们的app state,,一个react组件作为View做了两件事情: render和响应用户操作,于是connect就是将store中的必要数据作为props传递给react组件来render..并包装action creator用于响应用户操作时dispatch一个action。
connect中的API
connect会把state和dispatch转换成props传递给子组件
它会让我们传递的参数:mapStateToProps,mapDispatchToProps,mergeProps(可不填)和React组件。
mapStateToProps是后台的数据和值
mapDispatchToProps是方法
mapStateToProps 是一个普通的函数,当他被connect调用的时候会为他传递一个参数state,字面意思就是 匹配一个state给组件
mapStateToProps 需要负责的事情就是, 返回需要传递给子组件的state
然后connect会拿到返回的数据写入到react组件中,然后组件中就可以通过props读取数据啦
mapDispatchToProps
字面意思就是: 匹配dispatch给组件
与mapStateToProps 很像,接收store中的dispatch和props,使页面可以复写dispatch方法,通过mapDispatchToProps这个方法,把action creator变成方法赋值到props,每当调用这个方法的时候就会更新state
class Cell extends Component{
render(){
const { indexInLL,seq,title,author,album_title,duration,duractionStyle,play,addToPlayList,addToLocalList } = this.props;
return (
<tr className="cell" onDoubleClick ={play}>
<td style={{textAlign:"right"}}>{seq}</td>
<td>
<span className="m-icon m-heart" style={{color: this.props.heartColor}} onClick={addToLocalList.bind(this,indexInLL)}></span>
<span className="cell-add" onClick={addToPlayList}>+</span>
</td>
<td>{title}</td>
<td>{author}</td>
<td>{album_title}</td>
<td style={duractionStyle}>{duration}</td>
</tr>
);
}
};
const mapStateToProps = (state,ownsProps) =>{
let { song_list } = state.localPlayList;
let indexInLL = getIndex('song_id',ownsProps,song_list);
let heartColor = `${indexInLL===-1?'#cdd2d7':'#EB363F'}`;
let duractionStyle = ownsProps.durationShow ? {} : { display: "none" };
let duration = ownsProps.durationShow ? timeFormat(ownsProps.file_duration) : 0;
let seq = ownsProps.seq<=9?'0'+ownsProps.seq:ownsProps.seq;
let title = formatText(ownsProps.title);
let author = formatText(ownsProps.author);
let album_title = formatText(ownsProps.album_title);
return {
seq,
title,
author,
album_title,
duration,
indexInLL,
heartColor,
duractionStyle,
};
};
const mapDispatchToProps = (dispatch,ownProps) => {
return {
play: () => dispatch(playSpecialSong(ownProps.song_id,ownProps.info)),
addToPlayList: () => dispatch(addToPlayList(ownProps.info)),
addToLocalList: (index) => dispatch(addToLocalList(ownProps.info,index)),
}
};
export default connect(mapStateToProps,mapDispatchToProps)(Cell);