我正在尝试使用用户可以选择照片的应用,但在关闭并重新打开应用时,会在打开应用时显示照片。我正在尝试使用AsyncStorage存储照片信息,以便在应用重新打开时显示它。我不断得到一个[对象],所以我不确定这是承诺对象还是照片中的对象。甚至在我在Asyncstorage中保存照片之前,源代码似乎是[Object object],所以我很困惑。这是我的上下文代码:
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);
此外,在当前实现中,在设置avatarSource之前执行saveKey()
相反,只需这样做:
this.setState({avatarSource: source});
this.saveKey('GroundingPhoto', source);