简体   繁体   English

异步函数具有旧状态 React-Redux

[英]async function has old state React-Redux

I am working on a React project where user can upload and remove photos in projects.我正在开发一个 React 项目,用户可以在其中上传和删除项目中的照片。 After Uploading new image it should be visible to user only if corresponding projectis selected.上传新图像后,只有选择了相应的项目,用户才能看到它。 The solution is fairly simple to check解决方案很容易检查

if 
(selectedProject.projectID=== imageMetadata.projectID)

where在哪里

  • selectedProject.projectID: Id of currently selected project( Comming from Redux Store ) selectedProject.projectID:当前选中项目的Id(来自Redux Store)
  • imageMetadata.projectID: Id of project to which uploaded image belongs. imageMetadata.projectID:上传图片所属的项目ID。

All of this is being done inside an async function and the problem we are facing is that even after selectedAlbum.albumID is changed everywhere else, this function still has its old value.所有这些都是在一个异步函数中完成的,我们面临的问题是,即使在其他地方更改了selectedAlbum.albumID之后,该函数仍然具有其旧值。 Is it because the function is async?是因为函数是异步的吗?

This is my code:这是我的代码:

 let projectId = selectedProject.projectID;
 const responses = await Promise.all(
   filesToUpload.map( async (file) => {
     let res = await imageStoreApiHandler.uploadPhoto(file, projectId);
     notifyUploadProgress(count++, total, notifcationKey);
     if (res.status === 200) {
       let imageMetadata: any = res.data[0];
       if (selectedProject.projectID === imageMetadata.projectID) {
         addImage(imageMetadata);
       }
     }
     return res;
   }));

It's probably a closure problem where the uploadhandler keeps caching the first function.这可能是一个闭包问题,uploadhandler 一直缓存第一个函数。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Maybe write a function which will return a promise all array based on the parameters current project id.也许编写一个函数,该函数将根据当前项目 ID 的参数返回一个承诺所有数组。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM