本文共 2210 字,大约阅读时间需要 7 分钟。
react-redux
作用
react-redux
的作用就是将react
与redux
连接起来,将redux
中的store
传递到react
组件中
展示组件 | 容器组件 |
---|---|
目的 | 展现在页面 |
是否感知redux | 否 |
要获取数据 | this.props |
要改变数据 | 调用props中传入的action |
创建者 | 开发人员 |
总结一点:展示组件就是
react
,容器组件是redux
连接react
的
react-redux
的使用1、安装
npm install react-redux --save
2、react-redux
中使用到的方法
1、Provider
实质上就是将store
传递到容器组件,容器组件又传递数据到展示组件
...容器组件
2、connect
将容器组件连接到展示组件中,进行数据的传递
//connect是一个柯里化函数 export default connect(xxx)(展示组件)
3、一般我们利用redux
开发react
项目常见的项目目录
connect
1、connect
源码
connect函数传递三个参数,实际开发中一般都是传入前2个参数
...return function connect(mapStateToProps, mapDispatchToProps, mergeProps) { ...}...
mapStateToProps
是一个(函数类型),接收一个完整的redux
状态树作为参数,返回当前展示组件需要的状态树,返回的key
会当做props
传递到展示组件。mapDispatchToProps
是一个(对象或者函数类型),接收一个完整的redux
的dispatch
方法作为参数,返回当前组件相关部分的或者全部的的action
mergeProps
是一个(函数类型),如果指定这个函数,分别获得mapStateToProps
、mapDispatchToProps
返回值以及当前组件的props
作为参数2、mapStateToProps(state,[ownProps])
的解析
第一个参数是必填的,第二个参数是选填的
- 1、
state
返回的参数作为props
传递到展示组件- 2、
ownProps
表示当前容器组件中的属性
3、关于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
是对象(代码见上面)2、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);
3、直接使用装饰器(不需要单独创建容器组件)
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; .... }