簡體   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);

    }

在上面的代碼中,我嘗試使用 uploadBytes 函數在 firebase 存儲中上傳圖像,在上傳圖像后,我得到了存儲圖像的 downloadURL,我想將它的值放在 arr[index]["imageUrl"] 中,但是arr[index]["imageUrl"] 在獲取 downloadURL 之前首先進行更新,我收到 downloadURL 未定義的錯誤,那么如何解決這個問題? 我正在使用 react 18 和 firebase 版本 9。

當使用then()運行代碼以響應異步操作的完成時,任何需要在完成時運行的代碼都必須then()回調中。

所以

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);                    
            });
        });                
    }
}

為了使它更熟悉一點,您可以將 `` 標記為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);                    
    }
}

請注意,這不會改變任何有關實際行為的信息,並且所有異步調用仍將異步執行。 它只是一種更熟悉的代碼編寫方式。


如果您有要上傳的圖像列表,請務必使用for of而不是forEachPromise.all來檢測所有異步操作何時完成。

您可以將更新arr[index]["imageUrl"]值的代碼移動到您檢索downloadURLthen塊中。 這將確保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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM