【问题标题】:The useState is not being updated correctly in a loopuseState 未在循环中正确更新
【发布时间】:2022-02-06 17:52:11
【问题描述】:

我正在开发一个证书生成器,其中我有一个名称列表,我想通过这些名称进行分析并将它们显示在证书上,然后将该证书下载为 pdf。然后我继续下一个名字等等。

const _exportPdf = async () => {

    // if namelist is not uploaded 
    if (nameList == null){
      console.log("Name List not uploaded");
      return;
    }

    // if name is uploaded 
    Object.keys(nameList).forEach(async function(key){
      const name = nameList[key];
      // export the certificate as a pdf 
      await html2canvas(document.querySelector("#capture")).then(canvas => { 
        console.log("exporting "+name);
        setVisibleName(name);
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF('l', 'pt', "a4");
        const imgProps= pdf.getImageProperties(imgData);
        var width = pdf.internal.pageSize.getWidth();
        var height = (imgProps.height * width) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0,width, height);
        const filename = name + ".pdf";
        pdf.save(filename); 
    }) 
   });

  }

目前我的样本名称列表中有5个名称,当我使用此功能时,我可以看到证书上的名称发生了变化,但是所有下载的5个证书上都写有“样本名称”(样本名称是默认值的可见名称)。

需要帮助。

【问题讨论】:

    标签: reactjs async-await react-hooks jspdf


    【解决方案1】:

    首先forEach async-await 不起作用,正如您所期望的那样。所以请改用for/ for of。

    【讨论】:

    • 我刚试了一下,还是不行,
    【解决方案2】:

    首先,您使用的是forEach,其中promise 不起作用,因为JS 引擎不会等待promise 被解析/拒绝,而是将promise 放入队列并继续执行循环,其次,您正在使用await 和then 来解决/拒绝相同的承诺。 使用.then 语法或await 语法。

    const names = Object.keys(nameList)
    for(name of names){
          // export the certificate as a pdf 
            const canvas = await html2canvas(document.querySelector("#capture")) //Wait for the promise to resolve/reject. Recommend to wrap it in try-catch block to handle errors.
            console.log("exporting "+name);
            setVisibleName(name);
            const imgData = canvas.toDataURL('image/png');
            const pdf = new jsPDF('l', 'pt', "a4");
            const imgProps= pdf.getImageProperties(imgData);
            var width = pdf.internal.pageSize.getWidth();
            var height = (imgProps.height * width) / imgProps.width;
            pdf.addImage(imgData, 'PNG', 0, 0,width, height);
            const filename = name + ".pdf";
            pdf.save(filename); 
    }
    

    此外,您还没有提到您在哪里以及如何准确地使用状态变量,但很可能由于不正确地使用承诺而得到错误的结果。记住状态中的更新会导致组件重新渲染。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 2023-01-05
      • 2021-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多