美文网首页ReactNativejavascript高级react
关于react-redux中的connect用法介绍及原理解析

关于react-redux中的connect用法介绍及原理解析

作者: 7天苹果 | 来源:发表于2017-04-24 21:27 被阅读19580次

关于react-redux的一个流程图

流程图

connect用法介绍

connect方法声明:

connect([mapStateToProps], [mapDispatchToProps], [mergeProps],[options])

作用:连接React组件与 Redux store


参数说明:

mapStateToProps(state, ownProps) : stateProps

这个函数允许我们将 store 中的数据作为 props 绑定到组件上。

const mapStateToProps = (state) => {
  return {
    count: state.count
  }
}

(1)这个函数的第一个参数就是 Redux 的 store,我们从中摘取了 count 属性。你不必将 state 中的数据原封不动地传入组件,可以根据 state 中的数据,动态地输出组件需要的(最小)属性。

(2)函数的第二个参数 ownProps,是组件自己的 props。有的时候,ownProps 也会对其产生影响。

当 state 变化,或者 ownProps 变化的时候,mapStateToProps 都会被调用,计算出一个新的 stateProps,(在与 ownProps merge 后)更新给组件。


mapDispatchToProps(dispatch, ownProps): dispatchProps

connect 的第二个参数是 mapDispatchToProps,它的功能是,将 action 作为 props 绑定到组件上,也会成为 MyComp 的 props。


[mergeProps],[options]

不管是 stateProps 还是 dispatchProps,都需要和 ownProps merge 之后才会被赋给组件。connect 的第三个参数就是用来做这件事。通常情况下,你可以不传这个参数,connect 就会使用 Object.assign 替代该方法。

[options] (Object) 如果指定这个参数,可以定制 connector 的行为。一般不用。


原理解析

首先connect之所以会成功,是因为Provider组件:

  • 在原应用组件上包裹一层,使原来整个应用成为Provider的子组件
  • 接收Redux的store作为props,通过context对象传递给子孙组件上的connect

那connect做了些什么呢?

它真正连接 Redux 和 React,它包在我们的容器组件的外一层,它接收上面 Provider 提供的 store 里面的 state 和 dispatch,传给一个构造函数,返回一个对象,以属性形式传给我们的容器组件。


关于它的源码

connect是一个高阶函数,首先传入mapStateToProps、mapDispatchToProps,然后返回一个生产Component的函数(wrapWithConnect),然后再将真正的Component作为参数传入wrapWithConnect,这样就生产出一个经过包裹的Connect组件,该组件具有如下特点:

  • 通过props.store获取祖先Component的store
  • props包括stateProps、dispatchProps、parentProps,合并在一起得到nextState,作为props传给真正的Component
  • componentDidMount时,添加事件this.store.subscribe(this.handleChange),实现页面交互
  • shouldComponentUpdate时判断是否有避免进行渲染,提升页面性能,并得到nextState
  • componentWillUnmount时移除注册的事件this.handleChange

由于connect的源码过长,我们只看主要逻辑:

export default function connect(mapStateToProps, mapDispatchToProps, mergeProps, options = {}) {
  return function wrapWithConnect(WrappedComponent) {
    class Connect extends Component {
      constructor(props, context) {
        // 从祖先Component处获得store
        this.store = props.store || context.store
        this.stateProps = computeStateProps(this.store, props)
        this.dispatchProps = computeDispatchProps(this.store, props)
        this.state = { storeState: null }
        // 对stateProps、dispatchProps、parentProps进行合并
        this.updateState()
      }
      shouldComponentUpdate(nextProps, nextState) {
        // 进行判断,当数据发生改变时,Component重新渲染
        if (propsChanged || mapStateProducedChange || dispatchPropsChanged) {
          this.updateState(nextProps)
            return true
          }
        }
        componentDidMount() {
          // 改变Component的state
          this.store.subscribe(() = {
            this.setState({
              storeState: this.store.getState()
            })
          })
        }
        render() {
          // 生成包裹组件Connect
          return (
            <WrappedComponent {...this.nextState} />
          )
        }
      }
      Connect.contextTypes = {
        store: storeShape
      }
      return Connect;
    }
  }

connect使用实例

这里我们写一个关于计数器使用的实例:

Component/Counter.js

import React, {Component} from 'react'

class Counter extends Component {
    render() {
        //从组件的props属性中导入四个方法和一个变量
        const {increment, decrement, counter} = this.props;
        //渲染组件,包括一个数字,四个按钮
        return (
            <p>
                Clicked: {counter} times
                {' '}
                <button onClick={increment}>+</button>
                {' '}
                <button onClick={decrement}>-</button>
                {' '}
            </p>
        )
    }
}

export default Counter;

Container/App.js

import { connect } from 'react-redux'
import Counter from '../components/Counter'
import actions from '../actions/counter';

//将state.counter绑定到props的counter
const mapStateToProps = (state) => {
    return {
        counter: state.counter
    }
};
//将action的所有方法绑定到props上
const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        increment: (...args) => dispatch(actions.increment(...args)),
        decrement: (...args) => dispatch(actions.decrement(...args))
    }
};

//通过react-redux提供的connect方法将我们需要的state中的数据和actions中的方法绑定到props上
export default connect(mapStateToProps, mapDispatchToProps)(Counter)

完整代码

Github:https://github.com/lipeishang/react-redux-connect-demo

相关文章

网友评论

  • Trance_b54c:请问你在IE中可以运行成功么.
  • 诗和远方何你:这个函数的第一个参数就是 Redux 的 store!!!!!
  • 秋夜已凉:正好项目中用到
  • _摩西_:...args是不是跟拆包表示法一样
  • 4f31c8959de0:按描述说,connect只接收了Provider提供的store里面的state和dispatch,但是Provider又接收Redux的store作为props,那想问下这里的connect是不是事实上接收的是Provider提供的props呢。Redux.store 等同于 props ,connect 接收的是 Provider的store的state和dispatch,那么mapStateToProps里面的state又是什么呢?
    7天苹果:connect 函数不会修改传入的 React 组件,返回的是一个新的已与 Redux store 连接的组件。mapStateToProps 函数接收整个 Redux store 的 state 作为 props,然后返回一个传入到组件 props 的对象。
  • 秃鹫的晚餐:mapStateToProps 这个函数的第一个参数是 redux的store 。这边是不是有点写错啊 应该是 是redux的store.getState()..不是很懂
    7天苹果:嗯,可以理解为保存在store中的state
  • 六小六的世界:膜拜一下
  • b79bba37dd1b:你好, 父组件里如何获取到子组件的实例呢? (如果子组件被connect链接起来的话), 不知道大神能否看见评论, 先谢过大神
    7天苹果:@b79bba37dd1b redux因为有了Provider组件和connect方法了之后,所有的组件的属性都会放在Provider组件的store里,这里就把Provider组件看成所有的组件的父组件就好了。
  • feeling_1f11: const {increment, decrement, counter} = this.props;这一句理解的不是特别明白,有时间您能解释一下吗
    7天苹果: @feeling_1f11 嗯,没事
    feeling_1f11:好的,已经明白了,谢谢了:sunglasses:
    7天苹果:这个是ES6新特性,叫做拆包表达式,你去网上看看就懂了。

本文标题:关于react-redux中的connect用法介绍及原理解析

本文链接:https://www.haomeiwen.com/subject/redyzttx.html