SetState在承诺后返回旧价值

发布于 2025-01-31 11:35:43 字数 538 浏览 3 评论 0原文

我将图像文件保存到S3 Amazon Web服务,然后检索链接后。 当链接从s3返回作为字符串时,请尝试将其保存到状态。但是,如果我们在Console.log(EditedProduct)中对其进行测试,则每次返回以前的值时设置了Productuct,但我需要新的。

      const imageSave = async (file: File, fileName: string) => {
         await modalProductUpload(file).then((s3payload) => {
             setEditedProduct({ ...editedProduct, [fileName]: s3payload.Location })
             console.log(s3payload.Location);
         });
         setTimeout(() => {
            console.log(editedProduct);
         }, 6000)
     }

I Saved image file to s3 amazon web service, and after retrieved the link.
When link returned from s3 as a string a try to save it to state.But if we test it in console.log(editedProduct),setEditedProduct every time return the previously value, but I need the new.

      const imageSave = async (file: File, fileName: string) => {
         await modalProductUpload(file).then((s3payload) => {
             setEditedProduct({ ...editedProduct, [fileName]: s3payload.Location })
             console.log(s3payload.Location);
         });
         setTimeout(() => {
            console.log(editedProduct);
         }, 6000)
     }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

零度° 2025-02-07 11:35:43

React将异步批量设置状态。您可以在useffect中获得更新的状态,并具有依赖性。

useEffect(() => { console.log(editedProduct); }, [editedProduct]);

React would batch set state asynchronously. You could get the updated state in the useEffect with having dependency as that state.

useEffect(() => { console.log(editedProduct); }, [editedProduct]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文