blog icon indicating copy to clipboard operation
blog copied to clipboard

react-redux

Open wuxianqiang opened this issue 4 years ago • 0 comments

Provider

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

export default class Provider extends Component {
  render() {
    return (
      <ReduxContext value={{ store: this.props.store }}>
        {this.props.children}
      </ReduxContext>
    );
  }
}

connect

import React, { Component } from 'react';
import { bindActionCreators } from './redux';
import ReduxContext from './context'

export default function (mapStateToProps, mapDispatchToProps) {
  return function (WrappedComponent) {
    return class extends Component {
      static contextType = ReduxContext
      constructor(props, context) {
        super(props);
        this.state = mapStateToProps(context.store.getState())
      }
      componentDidMount() {
        this.unsubscribe = this.context.store.subscribe(() => {
          this.setState(mapStateToProps(this.context.store.getState()))
        })
      }
      componentWillUnmount() {
        this.unsubscribe()
      }
      render() {
        let actions = {}
        if (typeof mapDispatchToProps === 'function') {
          actions = mapDispatchToProps(this.context.store.dispatch)
        } else {
          actions = bindActionCreators(mapDispatchToProps, this.context.store.dispatch)
        }
        return (
          <WrappedComponent dispatch={this.context.store.dispatch} {...this.state} {...actions}>

          </WrappedComponent>
        );
      }
    }
  }
}

// connect(mapStateToProps, mapDispatchToProps)(Component)

wuxianqiang avatar Apr 14 '20 23:04 wuxianqiang