-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Provider.js
92 lines (81 loc) · 2.14 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Context, { createHashFunction } from './Context'
import shallowEqual from '../utils/shallowEqual'
const ContextProvider = Context.Provider
class Provider extends Component {
constructor(props) {
super(props)
const state = props.store.getState()
this.state = {
state,
store: props.store,
hashFunction: createHashFunction(state)
}
this.unsubscribe = null
}
componentDidMount() {
this.isUnmounted = false
const state = this.state.store.getState()
this.unsubscribe = this.state.store.subscribe(this.triggerUpdateOnStoreStateChange.bind(this))
if (state !== this.state.state) {
this.setState({ state })
}
}
componentWillUnmount() {
this.isUnmounted = true
if (this.unsubscribe) this.unsubscribe()
}
componentDidUpdate(lastProps) {
const state = this.props.store.getState()
const storesEqual = lastProps.store === this.props.store
if (!storesEqual) {
if (this.unsubscribe) this.unsubscribe()
this.unsubscribe = this.props.store.subscribe(this.triggerUpdateOnStoreStateChange.bind(this))
this.setState({
state,
store: this.props.store
})
}
if(
!storesEqual ||
!shallowEqual(Object.keys(state), Object.keys(lastProps.store.getState()))
) {
this.setState({
hashFunction: createHashFunction(state)
})
}
}
triggerUpdateOnStoreStateChange() {
if (this.isUnmounted) {
return
}
this.setState(prevState => {
const state = prevState.store.getState()
if (prevState.state === state) {
return null
}
return {
state
}
})
}
render() {
const Context = this.props.context || ContextProvider
return (
<Context value={this.state}>
{this.props.children}
</Context>
)
}
}
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