About Redux connect

Time:2020-9-27
connect([mapStateToProps], [mapDispatchToProps], [mergeProps],[options])

mapStateToProps

mapStateToProps(state, ownProps) : stateProps

This function allows us to bind the data in the store to the component as props.

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

(1) The first parameter of this function is the store of Redux, from which we extract the count attribute. You don’t have to pass the data in the state into the component intact. You can output the (minimum) properties required by the component dynamically according to the data in the state.

(2) The second parameter of the function, ownprops, is the component’s own props. Sometimes, ownprops can also affect it.

When the state changes or ownprops changes, mapstatetoprops will be called to calculate a new stateprops (after merging with ownprops) and update it to the component

mapDispatchToProps

The second parameter of connect is mapdispatchtoprops. Its function is to bind action to component as props, which will also become props of mycomp.

[mergeProps],[options]

Both stateprops and dispatchprops need to be merged with ownprops before they are assigned to components. The third parameter of connect is used to do this. Usually, you can use connect without passing this parameter Object.assign Replace this method.

[options] (object) if you specify this parameter, you can customize the behavior of the connector. Generally not.

Principle analysis

firstConnect is successful because the provider component:

  • Wrap a layer on the original application component to make the original application a sub component of provider
  • Receive the store of Redux as props and pass it to connect on the descendant components through the context object

What does connect do?

It really connects Redux and react. It is packaged on the outer layer of our container component. It receives the state and dispatch in the store provided by the provider above, and sends it to a constructor. It returns an object and passes it to our container component in the form of attributes.

About its source code

Connect is a high-order function. Firstly, mapstatetoprops and mapdispatchtoprops are passed in, and then a function producing component (wrapwithconnect) is returned. Then, the real component is passed into wrapwithconnect as a parameter. In this way, a wrapped connect component is produced. The component has the following characteristics:

  • adopt props.store Get the store of ancestor component
  • Props include stateprops, dispatchprops and parentprops. They are combined to get nextstate, which is passed to the real component as props
  • When componentdidmount, the event is added this.store.subscribe ( this.handleChange ), realize page interaction
  • When shouldcomponentupdate, judge whether rendering is avoided, improve page performance, and get nextstate
  • Remove the registered event when componentwillunmount this.handleChange

Because the source code of connect is too long, we only look at the main logic:

export default function connect(mapStateToProps, mapDispatchToProps, mergeProps, options = {}) {
  return function wrapWithConnect(WrappedComponent) {
    class Connect extends Component {
      constructor(props, context) {
        //Get component from store
        this.store = props.store || context.store
        this.stateProps = computeStateProps(this.store, props)
        this.dispatchProps = computeDispatchProps(this.store, props)
        this.state = { storeState: null }
        //Merge stateprops, dispatchprops and parentprops
        this.updateState()
      }
      shouldComponentUpdate(nextProps, nextState) {
        //When the data changes, the component will render again
        if (propsChanged || mapStateProducedChange || dispatchPropsChanged) {
          this.updateState(nextProps)
            return true
          }
        }
        componentDidMount() {
          //Change the state of component
          this.store.subscribe(() = {
            this.setState({
              storeState: this.store.getState()
            })
          })
        }
        render() {
          //Generate package component connect
          return (
            <WrappedComponent {...this.nextState} />
          )
        }
      }
      Connect.contextTypes = {
        store: storeShape
      }
      return Connect;
    }
  }

So far, some of the above blogs are copied from other people’s articles
Original text: https://www.jianshu.com/p/4af…

The optimized implementation of connect is as follows
This is my own implementation. Now Redux does not do this. High order functions are not required in hooks

const Connect = (mapStateToProps: (state: any) => any) => {
  return function wrapWithConnect(WrappedComponent: any) {

    const Container = (props: any) => {
      const [state, dispatch] = useContext(StoreContext)
      const storeProps = mapStateToProps(state)
      return <ConnectComponent {...storeProps} dispatch={dispatch} {...props}/>
    }

    const ConnectComponent: React.FC<any> = React.memo((props) => {
      return <WrappedComponent {...props} />
    }, (prevProps, nextProps) => {
      return _.isEqual(prevProps, nextProps)
    })

    return Container
  }
}


export default Connect

ContainerIt can be regarded as a high-order function. Its main function is to compare whether the parameters of the new store and the old store change, and whether to prevent rendering

If useduseContextAs long as it is in a component, it will be rerender. There is no API to prevent it from rendering (trigger, like the one above me, put in the high-order function). Otherwise, all the functions of Redux can be completed by using the API of native react

Demo address: https://github.com/Grewer/red…

Recommended Today

Deep understanding of HTTP protocol

*Foreword: I’d like to share with you an article about my experience since I developed it, Let’s share a personal understanding of HTTP* -Maojiale😊 What are the methods of HTTP? HTTP 1.0 defines three request methods: get, post and head HTTP1.1 adds five request methods: options, put, delete, trace and connect What are the specific […]