forked from zbluephoenix/react-native-cached-image
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageCacheProvider.js
94 lines (72 loc) · 2.7 KB
/
ImageCacheProvider.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
'use strict';
const _ = require('lodash');
const React = require('react');
const ReactNative = require('react-native');
const PropTypes = require('prop-types');
const ImageCacheManagerOptionsPropTypes = require('./ImageCacheManagerOptionsPropTypes');
const ImageCacheManager = require('./ImageCacheManager');
const ImageCachePreloader = require('./ImageCachePreloader');
class ImageCacheProvider extends React.Component {
static propTypes = {
// only a single child so we can render it without adding a View
children: PropTypes.element,
// ImageCacheManager options
...ImageCacheManagerOptionsPropTypes,
// Preload urls
urlsToPreload: PropTypes.arrayOf(PropTypes.string).isRequired,
numberOfConcurrentPreloads: PropTypes.number.isRequired,
onPreloadComplete: PropTypes.func.isRequired,
};
static defaultProps = {
urlsToPreload: [],
numberOfConcurrentPreloads: 0,
onPreloadComplete: _.noop,
};
static childContextTypes = {
getImageCacheManager: PropTypes.func,
};
constructor(props) {
super(props);
this.getImageCacheManagerOptions = this.getImageCacheManagerOptions.bind(this);
this.getImageCacheManager = this.getImageCacheManager.bind(this);
this.preloadImages = this.preloadImages.bind(this);
}
getChildContext() {
const self = this;
return {
getImageCacheManager() {
return self.getImageCacheManager();
}
};
}
componentWillMount() {
this.preloadImages(this.props.urlsToPreload);
}
componentDidUpdate(prevProps, prevState, snapshot) {
// reset imageCacheManager in case any option changed
this.imageCacheManager = null;
// preload new images if needed
if (this.props.urlsToPreload !== prevProps.urlsToPreload) {
this.preloadImages(this.props.urlsToPreload);
}
}
getImageCacheManagerOptions() {
return _.pick(this.props, _.keys(ImageCacheManagerOptionsPropTypes));
}
getImageCacheManager() {
if (!this.imageCacheManager) {
const options = this.getImageCacheManagerOptions();
this.imageCacheManager = ImageCacheManager(options);
}
return this.imageCacheManager;
}
preloadImages(urlsToPreload) {
const imageCacheManager = this.getImageCacheManager();
ImageCachePreloader.preloadImages(urlsToPreload, imageCacheManager, this.props.numberOfConcurrentPreloads)
.then(() => this.props.onPreloadComplete());
}
render() {
return React.Children.only(this.props.children);
}
}
module.exports = ImageCacheProvider;