|
| 1 | +import createStoreShape from '../utils/createStoreShape'; |
| 2 | +import shallowEqual from '../utils/shallowEqual'; |
| 3 | +import isPlainObject from '../utils/isPlainObject'; |
| 4 | +import invariant from 'invariant'; |
| 5 | + |
| 6 | +export default function createConnector(React) { |
| 7 | + const { Component, PropTypes } = React; |
| 8 | + const storeShape = createStoreShape(PropTypes); |
| 9 | + |
| 10 | + return class Connector extends Component { |
| 11 | + static contextTypes = { |
| 12 | + store: storeShape.isRequired |
| 13 | + }; |
| 14 | + |
| 15 | + static propTypes = { |
| 16 | + children: PropTypes.func.isRequired, |
| 17 | + select: PropTypes.func.isRequired |
| 18 | + }; |
| 19 | + |
| 20 | + static defaultProps = { |
| 21 | + select: state => state |
| 22 | + }; |
| 23 | + |
| 24 | + shouldComponentUpdate(nextProps, nextState) { |
| 25 | + return !this.isSliceEqual(this.state.slice, nextState.slice) || |
| 26 | + !shallowEqual(this.props, nextProps); |
| 27 | + } |
| 28 | + |
| 29 | + isSliceEqual(slice, nextSlice) { |
| 30 | + const isRefEqual = slice === nextSlice; |
| 31 | + if (isRefEqual) { |
| 32 | + return true; |
| 33 | + } else if (typeof slice !== 'object' || typeof nextSlice !== 'object') { |
| 34 | + return isRefEqual; |
| 35 | + } |
| 36 | + return shallowEqual(slice, nextSlice); |
| 37 | + } |
| 38 | + |
| 39 | + constructor(props, context) { |
| 40 | + super(props, context); |
| 41 | + this.state = this.selectState(props, context); |
| 42 | + } |
| 43 | + |
| 44 | + componentDidMount() { |
| 45 | + this.unsubscribe = this.context.store.subscribe(::this.handleChange); |
| 46 | + this.handleChange(); |
| 47 | + } |
| 48 | + |
| 49 | + componentWillReceiveProps(nextProps) { |
| 50 | + if (nextProps.select !== this.props.select) { |
| 51 | + // Force the state slice recalculation |
| 52 | + this.handleChange(nextProps); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + componentWillUnmount() { |
| 57 | + this.unsubscribe(); |
| 58 | + } |
| 59 | + |
| 60 | + handleChange(props = this.props) { |
| 61 | + const nextState = this.selectState(props, this.context); |
| 62 | + if (!this.isSliceEqual(this.state.slice, nextState.slice)) { |
| 63 | + this.setState(nextState); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + selectState(props, context) { |
| 68 | + const state = context.store.getState(); |
| 69 | + const slice = props.select(state); |
| 70 | + |
| 71 | + invariant( |
| 72 | + isPlainObject(slice), |
| 73 | + 'The return value of `select` prop must be an object. Instead received %s.', |
| 74 | + slice |
| 75 | + ); |
| 76 | + |
| 77 | + return { slice }; |
| 78 | + } |
| 79 | + |
| 80 | + render() { |
| 81 | + const { children } = this.props; |
| 82 | + const { slice } = this.state; |
| 83 | + const { store: { dispatch } } = this.context; |
| 84 | + |
| 85 | + return children({ dispatch, ...slice }); |
| 86 | + } |
| 87 | + }; |
| 88 | +} |
0 commit comments