forked from quenice/react-native-cacheimage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCacheImage.js
110 lines (98 loc) · 2.84 KB
/
CacheImage.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import React from 'react'
import {DeviceEventEmitter, Image, ImageBackground} from 'react-native'
import CacheHelper from "./CacheHelper";
export default class CacheImage extends React.PureComponent {
state = {
source: undefined
}
listeners = []
componentDidUpdate(prevProps) {
const {source} = this.props
const {source: prevSource} = prevProps
if (!source && prevSource) {
this.updateSource()
return
}
if (source) {
if (!prevSource) {
this.update(source.uri)
return
}
if (source.uri != prevSource.uri) {
this.update(source.uri)
return
}
}
}
componentDidMount() {
const {source} = this.props
if(source && source.uri) {
this.update(source.uri)
}
}
componentWillUnmount() {
//remove listeners
if (!this.listeners || this.listeners.length === 0) return
for (let listener of this.listeners) {
try {
listener.remove()
} catch (e) {
CacheHelper.printLog(e)
}
}
}
render() {
const {children, ...props} = this.props
if (children) {
return <ImageBackground
{...props}
source={this.state.source}>
{children}
</ImageBackground>
} else {
return <Image
{...props}
source={this.state.source}/>
}
}
/**
* update state according to source.uri
* @param uri
*/
update(uri) {
//update state when the source.uri is local path
if (!CacheHelper.pattern.remoteUri.test(uri)) {
this.setState({source: this.props.source})
return
}
//do cache when source.uri is remote uri
CacheHelper.getImagePath(uri).then(cachePath => {
if (cachePath) this.updateSource({uri:cachePath})
else {
this.updateSource()
this.listeners.push(DeviceEventEmitter.addListener(CacheHelper.event.render, (originalUri, cachePath) => {
if (uri === originalUri) {
this.updateSource({uri: cachePath})
}
}))
}
}).catch((e) => {
this.updateSource({uri})
CacheHelper.printLog(e)
})
}
/**
* combine and update source in state
* @param source
*/
updateSource(source) {
if(!this) return
const {source: prevSource} = this.props
if (!prevSource || !source) {
this.setState({source})
return
}
source = Object.assign({}, prevSource, source)
this.setState({source})
}
}