@@ -5,57 +5,64 @@ import {ReactReduxContext} from './Context'
5
5
class Provider extends Component {
6
6
constructor ( props ) {
7
7
super ( props )
8
+
9
+ const { store} = props
10
+
8
11
this . state = {
9
- state : props . store . getState ( ) ,
10
- store : props . store
12
+ storeState : store . getState ( ) ,
13
+ store,
11
14
}
12
- this . unsubscribe = null
13
15
}
14
16
15
17
componentDidMount ( ) {
16
- this . isUnmounted = false
17
- const state = this . state . store . getState ( )
18
- this . unsubscribe = this . state . store . subscribe ( this . triggerUpdateOnStoreStateChange . bind ( this ) )
19
-
20
- if ( state !== this . state . state ) {
21
- this . setState ( { state } )
22
- }
18
+ this . _isMounted = true
19
+ this . subscribe ( )
23
20
}
24
21
25
22
componentWillUnmount ( ) {
26
- this . isUnmounted = true
27
- if ( this . unsubscribe ) this . unsubscribe ( )
23
+ if ( this . unsubscribe ) this . unsubscribe ( )
24
+
25
+ this . _isMounted = false
28
26
}
29
27
30
- componentDidUpdate ( lastProps ) {
31
- if ( lastProps . store !== this . props . store ) {
32
- if ( this . unsubscribe ) this . unsubscribe ( )
33
- this . unsubscribe = this . props . store . subscribe ( this . triggerUpdateOnStoreStateChange . bind ( this ) )
34
- this . setState ( {
35
- state : this . props . store . getState ( ) ,
36
- store : this . props . store
37
- } )
28
+ componentDidUpdate ( prevProps ) {
29
+ if ( this . props . store !== prevProps . store ) {
30
+ if ( this . unsubscribe ) this . unsubscribe ( )
31
+
32
+ this . subscribe ( )
38
33
}
39
34
}
40
35
41
- triggerUpdateOnStoreStateChange ( ) {
42
- if ( this . isUnmounted ) {
43
- return
44
- }
36
+ subscribe ( ) {
37
+ const { store} = this . props
45
38
46
- this . setState ( prevState => {
47
- const newState = prevState . store . getState ( )
48
- if ( prevState . state === newState ) {
49
- return null
50
- }
51
- return {
52
- state : newState
39
+ this . unsubscribe = store . subscribe ( ( ) => {
40
+ const newStoreState = store . getState ( )
41
+
42
+ if ( ! this . _isMounted ) {
43
+ return
53
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
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
+ }
55
61
}
56
62
57
63
render ( ) {
58
64
const Context = this . props . context || ReactReduxContext
65
+
59
66
return (
60
67
< Context . Provider value = { this . state } >
61
68
{ this . props . children }
0 commit comments