我正在尝试使用react-native imagepicker库创建可恢复的功能,但是当我导入函数时,我从导入它的组件中得到了不确定的信息。与console.log我看到它的实际工作。只是不显示上传的图片。
我尝试返回源代码和实际函数,但是它不起作用
helperfunction.js
import ImagePicker from 'react-native-image-picker';
export const photoUpload =()=>{
const options = {
title: 'Select Avatar',
camera: [{ name: 'fb', title: 'Take a picture' }],
storageOptions: {
skipBackup: true,
path: 'images',
},
};
const action = ImagePicker.showImagePicker(options, (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.camera) {
console.log('User tapped custom button: ', response.camera);
} else {
const source = { uri: response.uri };
console.log(source)
return source;
}
})
return action;
}
App.js
import {photoUpload} from '../../../utilities/helper/photoUpload'
handlePhotoUpload = async () =>{
const data = await photoUpload()
console.log(data) (this comes back undefined)
if (data){
this.setState({
photo: data
});
}
}
答案 0 :(得分:1)
如果您从文档中查看showImagePicker函数的签名,则会看到它没有返回值:
静态showImagePicker(选项?,回调)
仍然从控制台日志中看到结果的原因是,当您调用showImagePicker函数时,它正在异步调用回调函数。要解决此问题,您可以采用如下承诺:
export const photoUpload = () => {
const options = {
title: 'Select Avatar',
camera: [{name: 'fb', title: 'Take a picture'}],
storageOptions: {
skipBackup: true,
path: 'images',
},
};
return new Promise(((resolve, reject) => {
ImagePicker.showImagePicker(options, (response) => {
if (response.didCancel) {
reject('User cancelled image picker');
} else if (response.error) {
reject('ImagePicker Error: ', response.error);
} else if (response.camera) {
reject('User tapped custom button: ', response.camera);
} else {
const source = {uri: response.uri};
resolve(source);
}
})
}))
}
您可以将app.js保留为已经等待“ promise”,即“ await”,这意味着数据变量将导致来自promise的源结果对象