我正在尝试拥有一个应用程序,用户可以选择照片,但是在关闭并重新打开应用程序时,照片打开应用时会显示照片。我正在尝试使用asyncstorage存储照片信息,以便在应用程序重新打开时可以显示。我不断获得[对象对象],因此我不确定这是承诺对象还是照片中的对象。甚至在我将照片保存在Asyncstorage中之前,源似乎是[对象],所以我很困惑。这是我的上下文代码:
export default class GroundingBox extends React.Component {
constructor(props) {
super(props);
this.selectPhotoTapped = this.selectPhotoTapped.bind(this);
}
async saveKey(key, value){
value = JSON.stringify(value);
try {
await AsyncStorage.setItem(key, value);
} catch (error) {
// Error saving data
console.log("Error: could not save data" + error);
}
}
async getKey(key){
try {
var value = await AsyncStorage.getItem(key);
value = JSON.parse(value);
return value;
} catch (error) {
console.log("Error retrieving data" + error);
}
}
state = {
avatarSource: null,
songTitle: null,
};
async checkPhoto(){
source = await this.getKey('GroundingPhoto');
if (source != null){
console.log("This is what source does look like: " + source);
this.setState({
avatarSource: source
});
}
}
async checkSongTitle(){
if (await this.getKey('SongTitle') != null){
source = await this.getKey('SongTitle');
//console.log("This is what source does look like: " + source);
this.setState({
songTitle: source
});
}
}
async selectPhotoTapped() {
const options = {
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
storageOptions: {
skipBackup: true,
},
};
setTimeout(() => {
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled photo picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
let source = { uri: response.uri };
console.log("This is what source should look like: " + source);
this.setState({
avatarSource: source,
});
}
})
}, 500);
await this.saveKey('GroundingPhoto', this.state.avatarSource);
//console.log("AVATAR:" + this.state.avatarSource);
//TODO: Photo no longer saves upon app close
}
render() {
this.checkPhoto();
return (
<TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
<View
style={[
styles.avatar,
styles.avatarContainer,
{ marginBottom: 20 },
]}
>
{(this.state.avatarSource == null) ? (
<Button
type="custom"
backgroundColor={"#7bd2d8"}
borderColor={"#16a085"}
borderRadius={10}
shadowHeight={5}
containerStyle={styles.buttonContainer}
contentStyle={styles.content}
onPress={this.selectPhotoTapped.bind(this)}> Select a Photo </Button>
) : (
<Image style={styles.avatar} source={this.state.avatarSource} />
)}
</View>
SetState函数不会立即更改状态。因此,您不能简单地这样做:
this.setState({avatarSource: source});
await this.saveKey('GroundingPhoto', this.state.avatarSource);
此外,在当前实现中,saveKey()
在可以设置Avatarsource之前被执行
相反,只需这样做:
this.setState({avatarSource: source});
this.saveKey('GroundingPhoto', source);
我浏览了反应本形图像的文档,并找到了此
在iOS上,不要以为返回的绝对URI会持续存在。看 #107
尽管#107提出了一堆解决方案,但如果我是您,我宁愿存储图像的基本64,然后将其回收