【问题标题】:Unhandled Runtime Error - TypeError: Cannot read property 'length' of undefined (Nextjs)未处理的运行时错误-TypeError:无法读取未定义的属性“长度”(Nextjs)
【发布时间】:2021-07-03 03:30:43
【问题描述】:

我正在编写代码以接受二维码图像并解码为字符串。

图片将是Nextjs的“public”文件夹中的静态文件。

在我的代码中,我已将图像转换为“imageData”。我成功转换并获得了返回 A Uint8ClampedArray 的“imageData”对象。

然后,我使用这个 npm 库来做 javascript QR 阅读器。 https://www.npmjs.com/package/jsqr

但是,不知何故,它给了我这个错误。

未处理的运行时错误 TypeError:无法读取未定义的属性“长度”

这是在我的 localhost:3000 中显示的错误

当我查看我的代码编辑器时。我在第 372 行突出显示。

不过,我认为第 372 行是 .next 库的一部分,我不应该对它做任何事情。

那可能是我的代码。

这是我的代码。

index.js

import Head from 'next/head'
import styles from '../styles/Home.module.css'
import jsQR from 'jsqr'
import { useEffect } from 'react'

export default function Home() {

  useEffect(() => {
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext('2d');
    const width = 200;
    const height = 200;

    const image = new Image;
    var imageDataT
    image.src = './Test_QR_Coupon.png'
    image.onload = () => {
      ctx.drawImage(image, 0, 0,width,height);
      imageDataT = ctx.getImageData(0, 0, 200, 200);
      console.log(imageDataT);
    }

    const code = jsQR(imageDataT, 300, 300,'dontInvert')
    console.log('Code:', code)
    if (code) {
      console.log("Found QR code", code);
    }
  })

  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <canvas id="canvas"></canvas>
      </main>

      <footer className={styles.footer}>
        <a
          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
          target="_blank"
          rel="noopener noreferrer"
        >
          Powered by{' '}
          <img src="/vercel.svg" alt="Vercel Logo" className={styles.logo} />
        </a>
      </footer>
    </div>
  )
}

【问题讨论】:

  • .length 部分在哪里?请显示您在哪里使用它或者它是在某处使用它的库吗?
  • 我已经编辑了问题并显示了我在哪里使用了该库。 @Sowam

标签: reactjs next.js qr-code uint8t getimagedata


【解决方案1】:

您收到未定义的错误,因为您在定义 imageDataT 的 onload 回调之前调用了 jsqr 函数。您需要将代码包装在回调中。

var imageDataT
image.src = './Test_QR_Coupon.png'
image.onload = () => {
  ctx.drawImage(image, 0, 0,width,height);
  imageDataT = ctx.getImageData(0, 0, 200, 200);
  console.log(imageDataT);
  const code = jsQR(imageDataT, 300, 300,'dontInvert')
  console.log('Code:', code)
  if (code) {
    console.log("Found QR code", code);
  }
}

【讨论】:

    猜你喜欢
    • 2021-11-19
    • 2021-12-10
    • 2021-02-26
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 2022-01-13
    • 2019-02-18
    相关资源
    最近更新 更多