如何从扫描的二维码中检索数据?

How do I retrieve the data from a scanned QR Code?

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

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("");

These are the codes to generate a QR code for the current user. This would work however, once the user logs out, it won't recognize the auth.currentUser.uid anymore and would cause an error.

TypeError: Cannot read property 'uid' of null

  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");
    }
  };

These are the codes to scan the QR Code. I wanted to retrieve the data of the scanned QR code, however, it would cause an error in retrieving the document from firestore since it says that the scanResult should not be empty.

× FirebaseError: Function CollectionReference.doc() cannot be called with an empty path.

  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 个用户。 User1 注册并登录,将有一个基于 user1 的用户 ID 的二维码。 user2 将能够扫描 user1 的 QR 码,并能够看到 user1 的帐户详细信息。我正在练习如何实施这个过程。

没有用户登录时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")
  }, []);