-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathProvider.js
72 lines (57 loc) · 1.68 KB
/
Provider.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { ReactReduxContext } from './Context'
import Subscription from '../utils/Subscription'
class Provider extends Component {
constructor(props) {
super(props)
const { store } = props
this.notifySubscribers = this.notifySubscribers.bind(this)
const subscription = new Subscription(store)
subscription.onStateChange = this.notifySubscribers
this.state = {
store,
subscription
}
this.previousState = store.getState()
}
componentDidMount() {
this.state.subscription.trySubscribe()
if (this.previousState !== this.props.store.getState()) {
this.state.subscription.notifyNestedSubs()
}
}
componentWillUnmount() {
if (this.unsubscribe) this.unsubscribe()
this.state.subscription.tryUnsubscribe()
}
componentDidUpdate(prevProps) {
if (this.props.store !== prevProps.store) {
this.state.subscription.tryUnsubscribe()
const subscription = new Subscription(this.props.store)
subscription.onStateChange = this.notifySubscribers
this.setState({ store: this.props.store, subscription })
}
}
notifySubscribers() {
this.state.subscription.notifyNestedSubs()
}
render() {
const Context = this.props.context || ReactReduxContext
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
)
}
}
Provider.propTypes = {
store: PropTypes.shape({
subscribe: PropTypes.func.isRequired,
dispatch: PropTypes.func.isRequired,
getState: PropTypes.func.isRequired
}),
context: PropTypes.object,
children: PropTypes.any
}
export default Provider