|
1 | 1 | import React, { Component } from 'react' |
2 | 2 | import PropTypes from 'prop-types' |
3 | 3 | import { ReactReduxContext } from './Context' |
| 4 | +import Subscription from '../utils/Subscription' |
4 | 5 |
|
5 | 6 | class Provider extends Component { |
6 | 7 | constructor(props) { |
7 | 8 | super(props) |
8 | 9 |
|
9 | 10 | const { store } = props |
10 | 11 |
|
| 12 | + this.notifySubscribers = this.notifySubscribers.bind(this) |
| 13 | + const subscription = new Subscription(store) |
| 14 | + subscription.onStateChange = this.notifySubscribers |
| 15 | + |
11 | 16 | this.state = { |
12 | | - storeState: store.getState(), |
13 | | - store |
| 17 | + store, |
| 18 | + subscription |
14 | 19 | } |
| 20 | + |
| 21 | + this.previousState = store.getState() |
15 | 22 | } |
16 | 23 |
|
17 | 24 | componentDidMount() { |
18 | 25 | this._isMounted = true |
19 | | - this.subscribe() |
| 26 | + |
| 27 | + this.state.subscription.trySubscribe() |
| 28 | + |
| 29 | + if (this.previousState !== this.props.store.getState()) { |
| 30 | + this.state.subscription.notifyNestedSubs() |
| 31 | + } |
20 | 32 | } |
21 | 33 |
|
22 | 34 | componentWillUnmount() { |
23 | 35 | if (this.unsubscribe) this.unsubscribe() |
24 | 36 |
|
| 37 | + this.state.subscription.tryUnsubscribe() |
| 38 | + |
25 | 39 | this._isMounted = false |
26 | 40 | } |
27 | 41 |
|
28 | 42 | componentDidUpdate(prevProps) { |
29 | 43 | if (this.props.store !== prevProps.store) { |
30 | | - if (this.unsubscribe) this.unsubscribe() |
31 | | - |
32 | | - this.subscribe() |
| 44 | + this.state.subscription.tryUnsubscribe() |
| 45 | + const subscription = new Subscription(this.props.store) |
| 46 | + subscription.onStateChange = this.notifySubscribers |
| 47 | + this.setState({ store: this.props.store, subscription }) |
33 | 48 | } |
34 | 49 | } |
35 | 50 |
|
36 | | - subscribe() { |
37 | | - const { store } = this.props |
38 | | - |
39 | | - this.unsubscribe = store.subscribe(() => { |
40 | | - const newStoreState = store.getState() |
41 | | - |
42 | | - if (!this._isMounted) { |
43 | | - return |
44 | | - } |
45 | | - |
46 | | - this.setState(providerState => { |
47 | | - // If the value is the same, skip the unnecessary state update. |
48 | | - if (providerState.storeState === newStoreState) { |
49 | | - return null |
50 | | - } |
51 | | - |
52 | | - return { storeState: newStoreState } |
53 | | - }) |
54 | | - }) |
55 | | - |
56 | | - // Actions might have been dispatched between render and mount - handle those |
57 | | - const postMountStoreState = store.getState() |
58 | | - if (postMountStoreState !== this.state.storeState) { |
59 | | - this.setState({ storeState: postMountStoreState }) |
60 | | - } |
| 51 | + notifySubscribers() { |
| 52 | + this.state.subscription.notifyNestedSubs() |
61 | 53 | } |
62 | 54 |
|
63 | 55 | render() { |
|
0 commit comments