【问题标题】:I'm trying to display a message alert when the button is clicked单击按钮时,我正在尝试显示消息警报
【发布时间】:2021-12-15 08:25:59
【问题描述】:
export default function ProjectCard1() {
  
  const [open, setOpen] = React.useState(false);


  const handleClick = () => {
    setOpen(true).then(response => {
      window.open("https://project-uts-teori.vercel.app/");
    });

  };

  const handleClose = (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }
    setOpen(false);
  };
   

它说 TypeError: Cannot read properties of undefined (reading 'then')。我需要先显示警报消息,然后再将它 window.open 到站点。

【问题讨论】:

  • 你可以使用this语法。

标签: reactjs material-ui


【解决方案1】:

使用 useState 钩子设置值时,它不会返回承诺,这意味着您不能使用 .then 语法。相反,您需要使用 useEffect 挂钩并添加 open 作为依赖项。

export default function ProjectCard1() {
  
  const [open, setOpen] = React.useState(false);

  const handleClick = () => {
    setOpen(true)
  };

  React.useEffect(() => {
    if (open) {
      window.open("https://project-uts-teori.vercel.app/");
    }
  }, [open])

  const handleClose = (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }
    setOpen(false);
  };
}   

这样,每次open变量发生变化时都会调用useEffect函数,只有当值为true时才会重定向用户。

【讨论】:

    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 2015-06-04
    • 2011-11-15
    • 1970-01-01
    • 2015-07-15
    • 2018-04-06
    • 1970-01-01
    • 2023-02-06
    相关资源
    最近更新 更多