簡體   English   中英

React Custom Hook 使返回 Function 在事件上可執行

[英]React Custom Hook make return Function executable on an Event

我創建了一個自定義掛鈎來處理上傳到 AWS s3 存儲桶,但我面臨一個小問題。 我不想讓我的鈎子直接執行邏輯,所以我創建了一個可執行的 function 然后我要返回。 唯一的問題是沒有從handleUpload function內部設置state

這是我正在嘗試做的事情:

import React, { useState } from "react";

const useS3Aws = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [uploadedUrl, setUploadedUrl] = useState("");


  const handleUpload = async (file: any, s3FolderPath: string) => {
    setIsLoading(true); // the problem is here (state not being updated)

    // handle the uploading with AWS s3
    // code ......

    // setting the state with returned live url from s3
    setUploadedUrl("the live url"); // the problem is here (state not being updated)
    console.log(uploadedUrl); // it prints an empty string

    setIsLoading(true); // the problem is here (state not being updated)

  };

  return [
    isLoading,
    uploadedUrl,
    (file: any, s3FolderPath: string) => handleUpload(file, s3FolderPath),
  ] as const;
};

const UploadSong = () => {
  const [isLoading, uploadedUrl, handleUpload] = useS3Aws();

  const handleSong = async () => {

    const file = {
      // object data
    };


    handleUpload(file, "music");

    console.log(uploadedUrl); // it is empty

  };

  return (
    <div>
      <p>Live URL: {uploadedUrl ? uploadedUrl : "No Link"}</p>
      <button onClick={() => handleSong()}>
        Click me
      </button>
    </div>
  );
}

export default UploadSong;

游樂場鏈接

你的鈎子看起來不錯,但你沒有正確使用它的返回值。

<button onClick={() => handleSong}>

這實際上並沒有在點擊時調用handleSong 這會調用一個 function,它只在點擊時返回handleSong function。

你要:

<button onClick={() => handleSong()}>

或者,如果您不想通過 arguments,您可以:

<button onClick={handleSong}>

您可能會在這里感到困惑的一點:

console.log(uploadedUrl); // it is empty

當您設置 state 時,它是異步的。 State 已正確設置,但任何局部變量都會反映之前的 state,因為尚未發生重新渲染。 通常這根本不重要,因為正如您在此處看到的,當您單擊工作按鈕時,UI 會立即更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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