我的组件中包含此代码;
我要防止多次点击,因为它避免了我的阻止代码添加具有相同ID的元素,有人可以帮助我编写一个函数,例如setTimeOut()
或类似的东西,以防止第二次点击在1之后通过一秒或半秒,这样可以防止多次单击
state = {
redirect: false,
loading: false,
alreadyAddedFav: false,
}
onClickedHandler = (recipe_id, token) => {
if (!this.props.isAuthenticated) {
this.setState({ redirect: true })
}
else {
const favData = {
recipe_id: recipe_id,
userId: this.props.userId
}
if (this.props.favRecipes.length > 0) {
if (!this.props.favRecipes.some(item => item.recipe_id === recipe_id)) {
console.log("added in the loop!")
this.props.onFav(favData, token);
} else {
this.setState({ alreadyAddedFav: true })
console.log("it is already in the fav list!")
console.log(recipe_id)
}
} else {
this.props.onFav(favData, token);
}
}
}
render() {
return (
<SearchResult
key={ig.recipe_id}
title={ig.title}
imgSrc={ig.image_url}
clicked={() => this.onClickedHandler(ig.recipe_id, this.props.token)}
>
</SearchResult>)}
答案 0 :(得分:0)
创建实例变量lastClicked
然后在clickHandler中
if( new Date().getTime() - lastClicked < threshold ) {
return; // dont do anything
}
您的情况下的阈值为 1秒
答案 1 :(得分:0)
在您的状态下管理一个布尔属性,并基于该布尔值立即返回您的函数,因此,如果为true,这将防止用户多次单击。
state = {
redirect: false,
loading: false,
alreadyAddedFav: false,
isAlreadyClicked: false, // Initially false because user didn't clicked yet
}
onClickedHandler = (recipe_id, token) => {
/*
* If isAlreadyClicked is true immediatly return the function
* Which will prevent it's execution
*/
if (this.state.isAlreadyClicked) return;
// As user clicked and function execution starts so, make it true
this.setState({
isAlreadyClicked: true,
})
if (!this.props.isAuthenticated) {
this.setState({ redirect: true })
}
else {
const favData = {
recipe_id: recipe_id,
userId: this.props.userId
}
if (this.props.favRecipes.length > 0) {
if (!this.props.favRecipes.some(item => item.recipe_id === recipe_id)) {
console.log("added in the loop!")
this.props.onFav(favData, token);
// As now function did it's job return it back to the false
this.setState({
isAlreadyClicked: false,
})
} else {
this.setState({ alreadyAddedFav: true })
console.log("it is already in the fav list!")
console.log(recipe_id)
// As now function did it's job return it back to the false
this.setState({
isAlreadyClicked: false,
})
}
} else {
// As now function did it's job return it back to the false
this.setState({
isAlreadyClicked: false,
})
this.props.onFav(favData, token);
}
}
}
render() {
return (
<SearchResult
key={ig.recipe_id}
title={ig.title}
imgSrc={ig.image_url}
clicked={() => this.onClickedHandler(ig.recipe_id,
this.props.token)}
>
</SearchResult>
)
}