React-native Cloudinary 图片上传状态问题

问题描述 投票:0回答:2

我正在使用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
2个回答
0
投票

这个问题你解决了吗?我很想知道。我还遇到了 axios 调用的触发顺序问题,并且在向数据库发送请求时未设置状态。


-1
投票

这是一个完整的示例,由 OGcodes 使用直接调用 Cloudinary Rest API 以及 ImagePicker 组件完成。

© www.soinside.com 2019 - 2024. All rights reserved.