尝试让 Button 复制 URL 并使用 React Hooks 渲染 snackbar

Trying to get Button to copy URL and render snackbar using React Hooks

我还在学习 React Hooks。正如标题所述,当用户点击标记为 'Copy to Clipboard' 的按钮时,我当然希望它复制 url (它确实如此),然后我尝试使用 Effect 以便它也显示一个小吃店(来自 materialui)告诉用户网站已成功复制到剪贴板。

我遇到错误:

“期望赋值或函数调用,但却看到了表达式 no-unused-expressions”

我知道这与我如何在 useEffect 中调用“setopenWebsiteSnackbar”有关。我确定有一个我不理解的简单解决方案。

const [isCopiedWebsite, setCopiedWebsite] = useClipboard("https://www.websiteIwanttoCopy.com");

useEffect(() => {setopenWebsiteSnackbar,
    console.log("Website Copied")}, 
    [isCopiedWebsite]
    )

  const [openWebsiteSnackbar, setopenWebsiteSnackbar] = React.useState(false);
  const handleClickWebsite = () => {
  setopenWebsiteSnackbar(true);
  };
  const handleCloseWebsite = (event, reason) => {
      if (reason === 'clickaway') {
      return;
  }
  setopenWebsiteSnackbar(false);
};


return (
<Button variant="contained" size="large" color="secondary" onClick={setCopiedWebsite}>Copy to Clipboard</Button>

<div className={classes.root}>

<Snackbar open={openWebsiteSnackbar} autoHideDuration={6000} onClose={handleCloseWebsite }>
        <Alert onClose={handleCloseWebsite } severity="success">
        Website URL successfully copied!
        </Alert>
        </Snackbar>

)

setopenWebsiteSnackbar 是一个函数。您目前在其他地方调用该函数,例如:

setopenWebsiteSnackbar(true);

但是在你的 useEffect 中你并没有调用它,你只是有一个未使用的引用:

setopenWebsiteSnackbar,

这里的逗号也没有多大意义。您是要调用函数吗?:

useEffect(() => {
  setopenWebsiteSnackbar(true);
  console.log("Website Copied");
}, [isCopiedWebsite]);

基本上,如果您希望“效果”是小吃店打开,那么您需要调用该函数并更新该状态。