-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
62 lines (53 loc) · 1.37 KB
/
index.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
import React from 'react'
import equal from '@app-elements/equal'
const withState = optsOrMapper => PassedComponent => {
let mapper
let name
if (typeof optsOrMapper === 'function') {
mapper = optsOrMapper
} else {
mapper = optsOrMapper.mapper
name = optsOrMapper.name
}
class WithState extends React.Component {
constructor (props, { store }) {
super(props)
this._store = store
this._update = this._update.bind(this)
this._unsubscribe = store.subscribe(this._update)
this.state = {
...this.state,
_mappedState: mapper(store.getState(), props)
}
}
_update () {
const _mappedState = mapper(this._store.getState(), this.props)
if (!equal(_mappedState, this.state._mappedState)) {
this.setState({ _mappedState })
}
}
componentWillUnmount () {
this._unsubscribe()
}
componentDidUpdate () {
this._update()
}
render () {
const { _mappedState } = this.state
return (
<PassedComponent
store={this._store}
{...this.props}
{..._mappedState}
/>
)
}
}
const passedComponentName = PassedComponent.displayName ||
PassedComponent.name ||
name ||
'PassedComponent'
WithState.displayName = `withState(${passedComponentName})`
return WithState
}
export default withState