React-Redux common API

React-Redux Redux is based on a large number of repeated code which is encapsulated.

1. Provider

Using the provided context object to store all sub-components. No longer need to store all references in each component.

import React, { Component } from 'react';
import Context from './context';

// 给connect等方法提供store
export default class Provider extends Component {
  render() {
    return (
      <Context.Provider value={{store: this.props.store}}>
        {this.props.children}
      </Context.Provider>
    )
  }
}

2. connect

This method of encapsulating a large number of logical, mainly as follows:

1. The component properties used to connect a dispatch method of automatically binding method; this.props.dispatch 
 2. setState method to connect the component approach a state of the automatic warehouse added subscription 
 assembly 3. The connect method for the binding repository attribute state value; this.props.XXXX 
    no longer use the method store.getState 
 4. actions used to connect the components of the automated method using the method bindActionCreators
import React, { Component } from 'react';
import Context from './context';
import { bindActionCreators } from 'redux';

/**
 * 
 * @param {function} mapStateToProps 绑定state到组件的props
 * @param {funtion|object} mapDispatchToProps  返回actions对象
 */
export default function(mapStateToProps, mapDispatchToProps) {
  return function(WrappedComponent) {
    return class extends Component {
      static contextType = Context;
      constructor(props, context) {
        super(props);
         //Mapped state, i.e., the return value mapStateToProps, props components bound to 
        the this .STATE = mapStateToProps (context.store.getState ()); 
      } 
      componentDidMount () { 
        the this .unsubscribe = the this .context.store.subscribe ( () => {
           // the setState usage; a state object is passed 
          the this .setState (mapStateToProps ( the this .context.store.getState ())); 
        }) 
      } 
      componentWillUnmount () { 
        the this .unsubscribe (); 
      } 
      the render () {       
        const {dispatch} = the this .context.store; 
        the let Actions = {};
        if (typeof mapDispatchToProps === 'object'){
          actions = mapDispatchToProps;
        } 
        if (typeof mapDispatchToProps === 'function') {
          actions = mapDispatchToProps(dispatch);
        }
        const bindActions = bindActionCreators(actions, dispatch)
        return (
          <WrappedComponent dispatch={dispatch} {...this.state} {...bindActions} />          
        )
      }
    }
  }
}

 

Guess you like

Origin www.cnblogs.com/lyraLee/p/12074449.html