简体   繁体   English

在 React JS 中更新数组之前如何先运行一个函数?

[英]How to run a function first before updating the array in react JS?

const handleItinerary = (e, type) => {
        
        var index = parseInt(e.target.name);
        let arr = [...itinerary];
        
        if (type === "imageUrl") {
            
            const date = new Date().getTime();
            const storageRef = ref(storage, `${date}`);

            uploadBytes(storageRef, e.target.files[0]).then((snapshot) => {
                
                getDownloadURL(storageRef).then((downloadURL) => {
                    arr[index]["imageUrl"] = downloadURL;
                    
                });
            });
                
        }
            

        setitinerary(arr);

    }

In the above code I am trying to upload an image in firebase storage using uploadBytes function and after uploading the image I get the downloadURL where image is stored, I want to put its value in arr[index]["imageUrl"], but the arr[index]["imageUrl"] is getting updated first before getting the downloadURL and I am getting error that downloadURL is undefined, so how to resolve this issue?在上面的代码中,我尝试使用 uploadBytes 函数在 firebase 存储中上传图像,在上传图像后,我得到了存储图像的 downloadURL,我想将它的值放在 arr[index]["imageUrl"] 中,但是arr[index]["imageUrl"] 在获取 downloadURL 之前首先进行更新,我收到 downloadURL 未定义的错误,那么如何解决这个问题? I am using react 18 and firebase version 9.我正在使用 react 18 和 firebase 版本 9。

When using then() to run code in response to an asynchronous operation being completed, any code that needs to run upon completion has to be inside that then() callback.当使用then()运行代码以响应异步操作的完成时,任何需要在完成时运行的代码都必须then()回调中。

So所以

const handleItinerary = (e, type) => {
    var index = parseInt(e.target.name);
    let arr = [...itinerary];
    
    if (type === "imageUrl") {
        const date = new Date().getTime();
        const storageRef = ref(storage, `${date}`);

        uploadBytes(storageRef, e.target.files[0]).then((snapshot) => {
            getDownloadURL(storageRef).then((downloadURL) => {
                arr[index]["imageUrl"] = downloadURL;
                setitinerary(arr);                    
            });
        });                
    }
}

To make this a bit more familiar, you can mark the `` as async and use await inside it:为了使它更熟悉一点,您可以将 `` 标记为async并在其中使用await

const handleItinerary = async (e, type) => {
    var index = parseInt(e.target.name);
    let arr = [...itinerary];
    
    if (type === "imageUrl") {
        const date = new Date().getTime();
        const storageRef = ref(storage, `${date}`);

        const snapshot = await uploadBytes(storageRef, e.target.files[0]);
        const downloadURL = await getDownloadURL(storageRef);
        arr[index]["imageUrl"] = downloadURL;
        setitinerary(arr);                    
    }
}

Note that this doesn't change anything about the actual behavior and all asynchronous calls are still executed asynchronously.请注意,这不会改变任何有关实际行为的信息,并且所有异步调用仍将异步执行。 It is merely a more familiar way to write the code.它只是一种更熟悉的代码编写方式。


If you have a list of images to upload, be sure to either use for of instead of forEach or Promise.all to detect when all asynchronous operations are done.如果您有要上传的图像列表,请务必使用for of而不是forEachPromise.all来检测所有异步操作何时完成。

You can move the code that updates the arr[index]["imageUrl"] value inside the then block where you retrieve the downloadURL .您可以将更新arr[index]["imageUrl"]值的代码移动到您检索downloadURLthen块中。 This will ensure that the arr[index]["imageUrl"] value is only updated after the downloadURL has been retrieved.这将确保arr[index]["imageUrl"]值仅在检索到downloadURL后更新。

const handleItinerary = (e, type) => {
  var index = parseInt(e.target.name);
  let arr = [...itinerary];

  if (type === "imageUrl") {
    const date = new Date().getTime();
    const storageRef = ref(storage, `${date}`);

    uploadBytes(storageRef, e.target.files[0]).then((snapshot) => {
      getDownloadURL(storageRef).then((downloadURL) => {
        arr[index]["imageUrl"] = downloadURL;
        setitinerary(arr);
      });
    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 state 在 React JS 中再次自动更新? - Why does the state is updating automatically again in React JS? 使用 React 在 Firestore 中更新 Doc 时遇到问题 - Trouble updating Doc in Firestore with React 如何在streambuilder中运行一次异步function - How to run async function once in streambuilder 如何运行在类中创建的函数? 安卓工作室 - How to run a function that was created in the class? Android Studio 无法从 function 源生成清单:TypeError:无法读取未定义的属性(读取“秘密”)反应 js 节点 js - Failed to generate manifest from function source: TypeError: Cannot read properties of undefined (reading 'secret') react js node js 如何将数组从组件传递到 C function - How to pass array from assembly to a C function React Native 如何从 Firebase Firestore 获取数组数据? - React Native how to fetch Array data from Firebase Firestore? 在 GitLab 管道之前运行预作业 - Run a pre job before GitLab pipeline 如何在 React 本机应用程序中过滤 Firebase Firestore Array 数据? - How to filter Firebase Firestore Array data in React native app? 在反应中渲染之前检查条件是否满足 - Check if a condition is satisfied before render in react
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM