Nextjs无法在异步函数调用后设置状态

时间:2021-07-30 08:48:07

标签: reactjs next.js

我有一个 Nextjs 表单,其中包含 FirstName、Age 和上传图片位置等字段。 填充表单并上传图像后(此时使用 URL.createObjectURL() 将上传的文件保存在状态变量中,工作正常),我想执行以下步骤:

  1. 首先将图像从状态变量上传到 cloudinary 服务器。

  2. 上传完成后,获取图片 url 和 setForm 以及其余字段。

             //helper function to upload images to Cloudinary server
             uploadImageToCloudinary(imageFile)
             .then((res)=>{
    
                 setForm({
                     ...form,
                     "picUploaded" : "true", //hard coded value for testing
                     "profilePic" : res.url //url is retrieved here successfully
                 });
    
                 //run validationafter upload to make sure required fields are there
                 let errs = validate();
                 setError(errs);
             })
    

验证码

    const validate= () => {
    console.log(form.picUploaded);// Output : true
    let err = {};
    if(!form.firstName){
      err.firstName= 'First Name is required.';
    }
    if(!form.lastName){
      err.lastName= 'Last Name is required.';
    }

    if(!form.profilePic){ //Issue : Profile pic is not set here
      err.profilePic= 'Profile Pic is required.';
    }

    return err;
 }

问题:上传的图片 url 未在表单(字段 profilePic)中设置,但设置了硬编码值 picUploaded。 有人可以指导我了解我在这里缺少什么。

1 个答案:

答案 0 :(得分:0)

问题是您在 setForm 调用后立即运行验证,它是异步的,因此您的验证将命中以前的表单值,而不是新的值。

为避免这种情况,您需要像这样单独运行验证。

useEffect(() => {
  setError(validate())      
}, [form])

这将在每次表单更新时运行验证,这取决于用例,您可能想要也可能不想要。

   uploadImageToCloudinary(imageFile)
     .then((res)=>{

         setForm({
             ...form,
             "picUploaded" : "true", //hard coded value for testing
             "profilePic" : res.url //url is retrieved here successfully
         });
     })
相关问题