forked from robinpowered/react-native-android-image-polyfill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
75 lines (67 loc) · 2.01 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
63
64
65
66
67
68
69
70
71
72
73
74
75
'use strict';
import React from 'react';
import {Image, Platform} from 'react-native';
const isAndroid = () => Platform.OS === 'android';
/**
* An extension of the Image class which fixes an Android bug where remote images wouldn't fire the
* Image#onError() callback when the image failed to load due to a 404 response.
*
* This component should only be used for loading remote images, not local resources.
*/
export default class ImagePolyfill extends React.Component {
static propTypes = Image.propTypes;
static defaultProps = Image.defaultProps;
constructor(props) {
super(props);
const { onError, source } = props;
if (isAndroid() && onError && source && source.uri) {
this.verifyImage();
}
this.state = {
source,
onError,
}
}
static getDerivedStateFromProps(nextProps, prevState){
if (nextProps.source && nextProps.source.uri &&
(!prevState.source || prevState.source.uri !== nextProps.source.uri) &&
isAndroid() &&
nextProps.onError
){
return {
source: nextProps.source,
onError: nextProps.onError,
};
} else {
return null;
}
}
componentDidUpdate(prevProps, prevState) {
const { source, onError } = this.state;
if (source && source.uri &&
(!prevState.source || prevState.source.uri !== source.uri) &&
isAndroid() &&
onError
){
this.verifyImage();
}
}
/**
* `Image.prefetch` is used to load the image and `catch` the failure.
* Android's `Image` `onError` callback does not get invoked if the remote image fails to load with a `404`.
* Prefetch, however, will reject the promise if it fails to load, allowing us to detect failures to
* provide better fallback support.
*
* Android only.
* https://github.com/facebook/react-native/issues/7440
*
* @return {void}
*/
verifyImage() {
var { uri } = this.props.source;
Image.prefetch(uri).catch(e => this.props.onError(e));
}
render() {
return <Image {...this.props} />;
}
}