wuxianqiang / blog

博客系列
17 stars 4 forks source link

react-redux #269

Open wuxianqiang opened 4 years ago

wuxianqiang commented 4 years ago

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)