我试图在AsyncStorage中存储图片,但是我不知道该怎么做,我应该存储uri还是路径?
我尝试过的有点废话,但是我尝试过:
state = {
avatarSource: null,
avatarSource2: null,
}
constructor(props) {
super(props);
this.state = {
modalVisible: false,
images: [{
url: '',
}],
}
this.setModalVisible = this.setModalVisible.bind(this)
}
saveData() {
AsyncStorage.getItem("uri");
}
然后当我选择我的图片时使用此:
selectImage = async () => {
ImagePicker.showImagePicker({ nodata: true, mediaType: 'photo' }, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
// You can also display the image using data:
// const source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: response.uri,
});
this.saveData; //here is where i save the data...
}
});
}
然后当我加载页面时...
componentWillMount() {
AsyncStorage.getItem('uri')
}
我的渲染就是这样...
render() {
return (
<ScrollView>
<View style={styles.container}>
<View style={styles.avatarContainer}>
<TouchableOpacity onPress={() => {
this.setModalVisible(!this.state.modalVisible, this.state.avatarSource);
}}>
{
this.state.avatarSource && <Image source={{ uri: this.state.avatarSource }} style={styles.avatar} />
}
</TouchableOpacity>
</View>
<Button title="Seleciona a imagem" onPress={this.selectImage} />
<View style={styles.avatarContainer}>
<TouchableOpacity onPress={() => {
this.setModalVisible(!this.state.modalVisible, this.state.avatarSource2);
}}>
{
this.state.avatarSource2 && <Image source={{ uri: this.state.avatarSource2 }} style={styles.avatar} />
}
</TouchableOpacity>
</View>
<Button title="Seleciona a imagem" onPress={this.selectImage2} />
</View>
<Modal style={styles.modalImage}
animationType='slide'
transparent={false}
visible={this.state.modalVisible}>
<TouchableHighlight style={{ backgroundColor: 'black' }} onPress={() => {
this.setModalVisible(!this.state.modalVisible) + this.props.navigation.navigate('Cartão de Cidadão');
}}>
<Icon active name="close" size={30} style={{ textAlign: 'center', marginTop: 0, color: 'white' }} />
</TouchableHighlight>
<ImageViewer imageUrls={this.state.images} />
</Modal>
</ScrollView>
);
}
}
我做错了什么? 谢谢。
答案 0 :(得分:1)
异步存储只能保存字符串。您可以将照片保存到文件系统。尝试使用此npm module
答案 1 :(得分:0)
轻松修复,将其存储到异步并在检索时进行解析时,您必须stringfy:
存储图像选择器:
AsyncStorage.setItem(@myKey,JSON.stringify(source));
检索:
const value = await AsyncStorage.getItem(@mykey)
if(value !== null) {
this.setState({ image: JSON.parse(value)});
}