react-redux
做用
react-redux
的做用就是将react
与redux
链接起来,将redux
中的store
传递到react
组件中javascript
展现组件 | 容器组件 |
---|---|
目的 | 展示在页面 |
是否感知redux | 否 |
要获取数据 | this.props |
要改变数据 | 调用props中传入的action |
建立者 | 开发人员 |
总结一点:展现组件就是
react
,容器组件是redux
链接react
的java
react-redux
的使用一、安装react
npm install react-redux --save
二、react-redux
中使用到的方法git
一、Provider
实质上就是将store
传递到容器组件,容器组件又传递数据到展现组件github
<Provider store={store}>
...容器组件
</Provider>
二、connect
将容器组件链接到展现组件中,进行数据的传递npm
//connect是一个柯里化函数
export default connect(xxx)(展现组件)
三、通常咱们利用redux
开发react
项目常见的项目目录redux
connect
一、connect
源码markdown
connect函数传递三个参数,实际开发中通常都是传入前2个参数ide
...
return function connect(mapStateToProps, mapDispatchToProps, mergeProps) {
...
}
...
mapStateToProps
是一个(函数类型),接收一个完整的redux
状态树做为参数,返回当前展现组件须要的状态树,返回的key
会当作props
传递到展现组件。mapDispatchToProps
是一个(对象或者函数类型),接收一个完整的redux
的dispatch
方法做为参数,返回当前组件相关部分的或者所有的的action
mergeProps
是一个(函数类型),若是指定这个函数,分别得到mapStateToProps
、mapDispatchToProps
返回值以及当前组件的props
做为参数二、mapStateToProps(state,[ownProps])
的解析函数
第一个参数是必填的,第二个参数是选填的
- 一、
state
返回的参数做为props
传递到展现组件- 二、
ownProps
表示当前容器组件中的属性
三、关于mapStateToProps
的代码
import {connect} from 'react-redux';
import * as ActionCreators from './../actions';
import Counter from './../components/Counter';
export default connect(
/** * 解析:mapStateToProps(state),返回一个counter以props传递给Counter组件中 * 关于state.counter1的解析,请参考下面的反向查找流程图 */
(state) =>({counter:state.counter1}),
ActionCreators
)(Counter);
connect
的写法mapStateToProps
是函数mapDispatchToProps
是对象(代码见上面)二、mapStateToProps
是函数mapDispatchToProps
也是函数
import {connect} from 'react-redux';
import Counter from './../components/Counter';
import {onIncrement,onDecrement,incrementIfOdd,incrementAsync} from './../actions';
export default connect(
state =>({counter:state.counter1}),
dispatch =>({
onIncrement:()=>dispatch(onIncrement())
})
)(Counter);
三、直接使用装饰器(不须要单首创建容器组件) 配置ES7的开发环境
import {connect} from 'react-redux';
import React, {Component} from 'react';
import * as ActionCreators from './../actions';
@connect(
state =>({counter:state.counter1}),
ActionCreators
)
export default class Counter extends Component {
constructor(props) {
super(props);
}
render() {
const {counter,onIncrement,onDecrement,incrementIfOdd,incrementAsync} = this.props;
....
}