这是我的组件,用于从用户手机中选择和上传照片。它工作正常,预计当用户打开手机照片库但随后决定取消并且不选择要上传的任何照片时,我会收到如下错误:
"YellowBox.js:82 可能的未处理的 Promise 拒绝 (id: 0): 错误:用户取消了图像选择“
我不知道在哪里以及如何捕获和处理错误,有什么帮助吗?
class ProfilePictureHandeler extends Component {
constructor (props) {
super(props)
this.state = {
loading: false,
dp: null
}
}
openPicker () {
this.setState({ loading: true })
const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob
const { currentUser } = firebase.auth()
ImagePicker.openPicker({
cropping: true,
height: 265,
width: 265,
mediaType: 'photo'
}).then(image => {
const imagePath = image.path
let uploadBlob = null
const imageRef = firebase.storage().ref(`/users/${currentUser.uid}/profile`).child('dp.jpg')
let mime = 'image/jpg'
fs.readFile(imagePath, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` })
})
.then((blob) => {
uploadBlob = blob
return imageRef.put(blob, { contentType: mime })
})
.then(() => {
uploadBlob.close()
return imageRef.getDownloadURL()
})
.then((url) => {
firebase.database().ref(`/users/${currentUser.uid}/profile`).update({
profile_picture: url
})
let obj = {}
obj['loading'] = false
obj['dp'] = url
this.setState(obj)
})
.catch((error) => {
console.log(error + 'OPEN PICKER AGAIN')
})
.catch((error) => {
console.log(error)
})
.catch((error) => {
console.log(error)
})
})
}
render () {
const selectedPicture = this.state.dp ? (<TouchableOpacity onPress={() => this.openPicker()}>
<Avatar
height={265}
rounded
source={{ uri: this.state.dp }}
activeOpacity={0.7}
/>
</TouchableOpacity>) : (
<TouchableHighlight onPress={() => this.openPicker()} >
<Avatar
rounded
height={265}
source={require('../../src/assets/man.png')}
activeOpacity={0.7}
/>
</TouchableHighlight>
)
// Default picture, d
const standardPicture = this.state.loading ? <ActivityIndicator animating={this.state.loading} /> : (
<View>
{selectedPicture}
</View>
)
return (
<TouchableHighlight onPress={() => this.openPicker()} >
<View>
{standardPicture}
</View>
</TouchableHighlight>
)
}
}
export default ProfilePictureHandeler
最佳答案
ImagePicker.openPicker()
如果用户取消选择图像,将会抛出错误。
尝试在代码中添加一个catch
,如下所示:
ImagePicker.openPicker(options)
.then(image => {
// do your stuff
})
.catch(error => {
// add this to your code
});
关于javascript - 从 react native 退出上传照片时出现未处理的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49871394/