javascript - 当用户更改按钮时 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 语句就会执行。
如何删除第二次执行,即一旦我单击按钮它会给我响应,并且在我登录后,它不应该再次给我响应,直到我再次单击它。
解决方案
你正在订阅一个 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");
}
};
推荐阅读
- shell - 在 Shell 脚本中使用 sed
- c++ - 在 Windows XP 中使 MinGW-64 编译的程序自包含时出现问题
- javascript - JXG 图形填充立方体
- python - 如何用 return None 替换引发异常
- javascript - Document.querySelector 返回多个分支
- python - Discord.py:不能使用普通命令并嵌入到同一个程序中
- google-sheets - 单行查询的堆叠结果
- azure - 将文件从 Azure ADLS G2 复制到 Azure 数据仓库,无需暂存
- javascript - 如何通过一次性权限请求在传单 js 上查看用户位置?
- swiftui - 如何设置NowPlayingView swiftui的样式