I want to cache images in the app, so they can load faster. The tutorial I found used FileSystem
from Expo, but I'm not using expo, so I found react-native-file-access
instead. After mounting, the code should check if the image exists, if not, download the image. I've tried but I can't seem to make it work.
import React, {Component} from 'react';
import {Image} from 'react-native';
import shorthash from 'shorthash';
import {Dirs, FileSystem} from 'react-native-file-access';
export default class CacheImage extends Component {
state = {
source: null,
};
componentDidMount = async () => {
const {uri} = this.props;
const name = shorthash.unique(uri);
const path = `${Dirs.CacheDir}/${name}`;
const image = await FileSystem.exists(path);
if (image.exists) {
this.setState({
source: {
uri: image.uri,
},
});
return;
}
/* Download image if one doesn't exist */
const newImage = await FileSystem.fetch(uri, {path: path})
.then(response => {
JSON.stringify(response);
})
.then(data => data);
this.setState({
source: {
uri: newImage.uri,
},
});
console.log('URI: ', this.state.source);
};
render() {
return <Image style={this.props.style} source={this.state.source} />;
}
}
the problem come from here
const newImage = await FileSystem.fetch(uri, {path: path})
.then(response => {
JSON.stringify(response);
})
.then(data => data);
you forget to return when use {}
const newImage = await FileSystem.fetch(uri, {path: path})
.then(response => {
return JSON.stringify(response);
})
.then(data => data);
I returned the response
without the JSON.stringify()
.
const newImage = await FileSystem.fetch(uri, {path: path})
.then(response => {
return response;
});
this.setState({
source: {
uri: newImage.url,
},
});
And I also removed the second .then()
because I still get the url
without adding it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.