[英]How can I get the uri from the fetch?
我想在應用程序中緩存圖像,以便它們可以更快地加載。 我發現的教程使用了 Expo 的FileSystem
,但我沒有使用 expo,所以我找到了react-native-file-access
。 掛載后,代碼應該檢查圖像是否存在,如果不存在,則下載圖像。 我試過了,但我似乎無法讓它工作。
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} />;
}
}
問題來自這里
const newImage = await FileSystem.fetch(uri, {path: path})
.then(response => {
JSON.stringify(response);
})
.then(data => data);
使用時忘記返回 {}
const newImage = await FileSystem.fetch(uri, {path: path})
.then(response => {
return JSON.stringify(response);
})
.then(data => data);
我返回了沒有JSON.stringify()
的response
。
const newImage = await FileSystem.fetch(uri, {path: path})
.then(response => {
return response;
});
this.setState({
source: {
uri: newImage.url,
},
});
而且我還刪除了第二個.then()
因為我仍然得到url
而不添加它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.