异步等待不起作用。我需要等待图像加载,进入一个状态然后继续前进。不起作用。
export default () => {
const [imgTmp, setImgTmp] = useState(null);
const chooseImage = async () => {
await ImagePicker.showImagePicker('', r => {
if (r.uri) {
let img = {uri: r.uri};
setImgTmp(img);
}
});
alert('...');
};
return (
<View>
<View style={{height: 40, backgroundColor: '#DDDD'}}>
<Image source={imgTmp} style={{width: 100, height: 100}} />
</View>
<Button title="Select Imagem" onPress={chooseImage} />
{imgTmp !== null ? (
<DynamicCollage width={400} height={400} images={imgTmp} matrix={[1]} />
) : null}
</View>
);
};
答案 0 :(得分:0)
ImagePicker.showImagePicker
不会返回Promise,因此等待它将无法按预期进行。
您可以做的是用Promise包装它:
const chooseImage = async () => {
try {
const img = await new Promise((resolve, reject) => {
ImagePicker.showImagePicker('', r => {
if (r.uri) {
const img = {uri: r.uri};
resolve(img);
}
reject("uri undefined");
});
});
setImgTmp(img);
alert('...');
} catch(e) {
// handle exception
console.log(e);
}
};