深入理解react-redux

xiaoxiao2021-02-28  91

一、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传递到容器组件,容器组件又传递数据到展示组件

<Provider store={store}> ...容器组件 </Provider>

2、connect将容器组件连接到展示组件中,进行数据的传递

//connect是一个柯里化函数 export default connect(xxx)(展示组件)

3、一般我们利用redux开发react项目常见的项目目录

四、深入理解connect

1、connect源码

connect函数传递三个参数,实际开发中一般都是传入前2个参数

... return function connect(mapStateToProps, mapDispatchToProps, mergeProps) { ... } ... 1、mapStateToProps是一个(函数类型),接收一个完整的redux状态树作为参数,返回当前展示组件需要的状态树,返回的key会当做props传递到展示组件。2、mapDispatchToProps是一个(对象或者函数类型),接收一个完整的redux的dispatch方法作为参数,返回当前组件相关部分的或者全部的的action3、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的写法

1、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、直接使用装饰器(不需要单独创建容器组件) 配置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; .... }

六、代码下载地址demo

转载请注明原文地址: https://www.6miu.com/read-39930.html

最新回复(0)