【问题标题】:How do I retrieve the data from a scanned QR Code?如何从扫描的二维码中检索数据?
【发布时间】:2021-08-01 06:23:04
【问题描述】:

我正在练习如何根据当前用户的用户 ID 生成二维码。一旦扫描特定用户的二维码,就会显示该用户的账户详情。我只是在练习,所以我可以熟悉这个过程是如何工作的。

import QRCode from "qrcode";
import QrReader from "react-qr-reader";


const QrCode = () => {
  const [text, setText] = useState("");
  const [image, setImage] = useState("");
  const [scanResult, setScanResult] = useState("");
  const [id, setID] = useState("");
  const [details, setDetails] = useState("");

这些是为当前用户生成二维码的代码。但是,这会起作用,一旦用户注销,它将不再识别 auth.currentUser.uid 并会导致错误。

TypeError: 无法读取 null 的属性 'uid'

  let user = auth.currentUser.uid;
  console.log(user);


  const generateQrCode = async () => {
    try {
      const response = await QRCode.toDataURL(user);
      setImage(response);
      console.log(response);
    } catch (err) {
      alert("error");
    }
  };

这些是扫描二维码的代码。我想检索扫描的 QR 码的数据,但是,它会导致从 firestore 检索文档时出错,因为它说 scanResult 不应该为空。

× FirebaseError:无法调用函数 CollectionReference.doc() 路径为空。

  const handleErrorWebCam = (error) => {
    alert("error scan");
  };

  const handleScanWebCam = (result) => {
    if (result) {
      setScanResult(result);
    }
  };

  useEffect(() => {
    const unsubscribe = firestore
      .collection("users")
      .doc(scanResult)
      .onSnapshot((snapshot) => {
        const arr = [];
        arr.push({
          ...snapshot.data(),
        });
        setDetails(arr);
        console.log(arr);
      });

    return () => {
      unsubscribe();
    };
  }, []);

  return (
    <Container>
      <Card>
        <h1> Just Trying First with QR Code</h1>
        {user}
        <CardContent>
          <Grid container spacing={2}>
            <Grid item xl={4} lg={4} md={6} sm={12} xs={12}>
              {/* {user} */}
              {/* <TextField
                label="Enter Text"
                value={user}
                // onChange={(e) => setText(e.target.value)}
              /> */}
              <Button variant="contained" onClick={() => generateQrCode()}>
                Submit
              </Button>
              <br />
              <br />
              <br />
              {image ? (
                <a href={image} download>
                  <img src={image} alt="img" />{" "}
                </a>
              ) : null}
            </Grid>
            <Grid item xl={4} lg={4} md={6} sm={12} xs={12}>
              <h1>Scanning</h1>
              <QrReader
                delay={300}
                style={{ width: "100%" }}
                onError={handleErrorWebCam}
                onScan={handleScanWebCam}
              />
              <h3>Scanned Result</h3>
              {scanResult}
            </Grid>
          </Grid>
        </CardContent>
      </Card>
    </Container>
  );
};

export default QrCode;

我实际上将使用类似的过程构建一个项目。会有2个用户。用户 1 注册并登录,将有一个基于用户 1 的用户 ID 的二维码。 user2 将能够扫描 user1 的 QR 码,并能够看到 user1 的帐户详细信息。我正在练习如何实现这个过程。

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore qr-code


    【解决方案1】:

    当没有用户登录时auth.currentUser为空。在生成二维码之前,你应该检查用户是否登录。

      const generateQrCode = async () => {
        try {
          const user = auth.currentUser
          if (!user) {
            alert("No user logged in")
          } else {
            const response = await QRCode.toDataURL(user.uid);
            setImage(response);
            console.log(response);
          }
        } catch (err) {
          alert("error");
        }
      };
    

    scanResult 的默认状态是空字符串。收到结果后运行查询:

      const handleScanWebCam = (result) => {
        if (result) {
          setScanResult(result);
          firestore
            .collection("users")
            .doc(result)
            .get()
            .then((snapshot) => {
              const arr = [];
              arr.push({
                ...snapshot.data(),
              });
              setDetails(arr);
              console.log(arr);
            });
        }
      };
    
      useEffect(() => {
        console.log("Use effect")
      }, []);
    

    【讨论】:

    • 如何从扫描的二维码中检索数据?在检索扫描的二维码数据时,我已将 scanResult 设置在 doc() 中
    • @AranyaDream 你能console.log(scanResult) 分享输出吗?
    • MiD7JmIOhXOmfDo14tKLi8DZg3y1,这是结果。就是生成的二维码中存储的userID
    • 如果二维码已经被扫描,它可以检索数据。但是,如果没有扫描到二维码,scanResult 将保持为空,因此,当从 firestore 检索数据时,它会显示此错误“FirebaseError: Function CollectionReference.doc() cannot be called with an empty path.”
    • 哦,没关系。我将 doc(scanResult) 更改为 doc(result) 并且它有效。谢谢
    猜你喜欢
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 2019-06-12
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    相关资源
    最近更新 更多