[英]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.