使用复制到剪贴板功能时如何防止UUID改变状态?

How to prevent UUID from changing state when using copy-to-clipboard function?

我设法将生成的 UUID 复制到我的剪贴板,但每当我单击按钮时,UUID(和 QR 码)都会更改,即使页面没有刷新。如何防止 UUID 改变其状态?请参考以下代码;

import React, { useState } from "react";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";
import FileCopyIcon from "@material-ui/icons/FileCopy";
import { v4 as uuid } from "uuid";
import QRCode from "react-qr-code";
import { CopyToClipboard } from "react-copy-to-clipboard";

export default function QRGenerator() {
  const adminId = uuid();

  const [qrcode, setQrcode] = useState({
    value: "",
    copied: false,
  });

  return (
    <div>
      <CopyToClipboard
        text={adminId}
        onCopy={() => setQrcode({ copied: true })}
      >
        <Button>
          <FileCopyIcon />
        </Button>
      </CopyToClipboard>

      <Typography align="center" variant="caption" paragraph="true">
        Admin ID : {adminId}
        {qrcode.copied ? <span style={{ color: "red" }}>Copied.</span> : null}
      </Typography>
      <QRCode value={adminId} />
    </div>
  );
}

每次状态改变时,都会调用渲染函数。所以uuid又被调用了,就变了。 如果你需要 uuid 是常量,我们可以使用 useState

  const [adminId] = useState(uuid());

或者我们必须将它作为 prop 从父组件传递,这样每次重新渲染它都不会改变。

您的代码片段有两个问题。

第一个:adminId

React hook在其生命周期内会被多次调用,根据uuid()

赋予不同的值

要解决它,你可以使用useStateuseRef或者将它移到QRGenerator函数之外。

第二期:更新状态

setQrcode({ copied: true })} 表示您将 qrcode 值替换为 { copied: true}undefined

下面的代码片段将解决上述问题

export default function QRGenerator() {
  const [adminId] = useState(uuid()); // or useRef(uuid());

  const [qrcode, setQrcode] = useState({
    value: "",
    copied: false,
  });

  return (
    <div>
      <CopyToClipboard
        text={adminId}
        onCopy={() => setQrcode({...qrcode, copied: true })} // this change only `copied` value
      >
        <Button>
          <FileCopyIcon />
        </Button>
      </CopyToClipboard>

      <Typography align="center" variant="caption" paragraph="true">
        Admin ID : {adminId}
        {qrcode.copied ? <span style={{ color: "red" }}>Copied.</span> : null}
      </Typography>
      <QRCode value={adminId} />
    </div>
  );
}

希望对您有所帮助!