Skip to content

Commit c31b94a

Browse files
committed
Initial re-implementation of connectAdvanced using hooks
Matches changes from v7.0.0-alpha.1
1 parent 16a66c4 commit c31b94a

File tree

3 files changed

+286
-146
lines changed

3 files changed

+286
-146
lines changed

src/components/Provider.js

Lines changed: 23 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,63 +1,55 @@
11
import React, { Component } from 'react'
22
import PropTypes from 'prop-types'
33
import { ReactReduxContext } from './Context'
4+
import Subscription from '../utils/Subscription'
45

56
class Provider extends Component {
67
constructor(props) {
78
super(props)
89

910
const { store } = props
1011

12+
this.notifySubscribers = this.notifySubscribers.bind(this)
13+
const subscription = new Subscription(store)
14+
subscription.onStateChange = this.notifySubscribers
15+
1116
this.state = {
12-
storeState: store.getState(),
13-
store
17+
store,
18+
subscription
1419
}
20+
21+
this.previousState = store.getState()
1522
}
1623

1724
componentDidMount() {
1825
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+
}
2032
}
2133

2234
componentWillUnmount() {
2335
if (this.unsubscribe) this.unsubscribe()
2436

37+
this.state.subscription.tryUnsubscribe()
38+
2539
this._isMounted = false
2640
}
2741

2842
componentDidUpdate(prevProps) {
2943
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 })
3348
}
3449
}
3550

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()
6153
}
6254

6355
render() {

0 commit comments

Comments
 (0)