【发布时间】:2022-01-14 10:56:09
【问题描述】:
我正在使用 react-native 和 EXPO CLI 构建一个应用程序,并且我有一个屏幕,我在注册过程中从用户那里获取一张/几张图片。 我想从用户的图库中获取图片,然后将其上传到 cloudinary 并生成一个 url,然后将此 url 推送到数据库中,然后在屏幕上呈现。
图片已成功上传到 Cloudinary,但它没有及时返回 url,当我将数据推送到数据库时,在 'imagesUrl' 状态下解析为空。 所以基本上在 Cloudinary 中过了一段时间后,我看到了我的图像,但是在“图像”字段下的数据库中,我得到了一个空数组,该数组被设置为当时也是空的状态。 setState 工作不正常。
我的代码:
本地状态:
const [images, setImages] = useState([]);
const [imagesUrl, setImagesUrl] = useState([]);
负责从用户图库中挑选图片的函数:
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
if (images.length < 6) setImages((prev) => [...prev, result]);
}
};
负责上传到 Cloudinary 的函数:
const handleUploads = async (files) => {
const formData = new FormData();
for (let i = 0; i <= files.length; i++) {
let file = files[i];
formData.append("file", file);
formData.append("upload_preset", "wingman");
formData.append("cloud_name", "drsgaixjb");
const res = await fetch(`${CLOUDINARY_URL}/image/upload`, {
method: "POST",
body: formData,
});
const cloudinaryFiles = await res.json();
setImagesUrl([...imagesUrl, cloudinaryFiles.url]);
}
};
负责将用户上传的文件转换为正确类型的函数:
const handleImagesType = (imgs) => {
let newImages = [];
imgs.forEach((img) => {
newImages.push({
uri: img.uri,
type: `test/${img.uri.split(".")[1]}`,
name: `test/${img.uri.split(".")[1]}`,
});
});
return newImages;
};
最后一个负责将数据推送到数据库的函数:
const pushDataHandler = async (data) => {
if (data.length) {
const temp = handleImagesType(data);
handleUploads(temp);
await db.collection("users").doc(firebase.auth().currentUser.uid).update({
images: imagesUrl,
});
}
};
当用户按下按钮提交图片时:
onPress={() => {
pushDataHandler(images);
dispatch(pullUserData()); //Pulling all the data of a user from DB to a redux state
}}
【问题讨论】:
标签: javascript react-native expo cloudinary