首页 > 解决方案 > 当用户更改按钮时 onClick 再次执行

问题描述

当我还没有登录并单击按钮时:它会先发出警报以登录然后一旦我用谷歌登录(通过firebase auth)然后脚本再次执行,这一次它作为登录功能执行并推送我到另一页...

<Button
key={q}
id={q}
onClick={handleClick}
>
  some Text
</Button>

这是handleClick函数:-

const handleClick = (e) => {
  e.preventDefault();
  let name = e.target.offsetParent.id;
  firebase.auth().onAuthStateChanged(function (user) { 
    if (user) {
      history.push("/testPage/" + btoa(name));
    }else{
      window.alert("Login To Continue");
    }
  });
};

在登录之前,当我单击按钮时执行 else 语句......但只要我登录,然后不单击任何按钮,if 语句就会执行。

如何删除第二次执行,即一旦我单击按钮它会给我响应,并且在我登录后,它不应该再次给我响应,直到我再次单击它。

标签: javascriptfirebasefirebase-authentication

解决方案


你正在订阅一个 observable。每次可观察者触发时,都会调用您的观察者。您可以存储该函数返回的订阅以取消订阅。或者您可以不订阅 observable 并使用该属性:

const handleClick = (e) => {
  e.preventDefault();
  let name = e.target.offsetParent.id;
  const user = firebase.auth().currentUser; 
  if (user) {
    history.push("/testPage/" + btoa(name));
  }else{
    window.alert("Login To Continue");
  }
};

推荐阅读