Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我的函数会无意中执行两次?_Javascript_Reactjs_Firebase_React Native_Components - Fatal编程技术网

Javascript 为什么我的函数会无意中执行两次?

Javascript 为什么我的函数会无意中执行两次?,javascript,reactjs,firebase,react-native,components,Javascript,Reactjs,Firebase,React Native,Components,我有一个构造函数,get方法,componentDidMount和componentWillUnmount方法。我只想监听一个scroll事件,并根据它调用get方法。如果滚动条位于页面底部,则一次调用get方法。这就是全部。第一个调用,即componentDidmount(),工作了一次,但当我向下滚动时,get方法工作了两次。我不希望它执行多次 这是我的代码: 构造函数(道具){ 超级(道具); 游标=-1 id=auth().currentUser.providerData[0]。uid

我有一个构造函数,get方法,componentDidMount和componentWillUnmount方法。我只想监听一个scroll事件,并根据它调用get方法。如果滚动条位于页面底部,则一次调用get方法。这就是全部。第一个调用,即componentDidmount(),工作了一次,但当我向下滚动时,get方法工作了两次。我不希望它执行多次

这是我的代码:

构造函数(道具){
超级(道具);
游标=-1
id=auth().currentUser.providerData[0]。uid
此.state={
点击次数:[],
孤岛加载:false,
过:错,
第一个电话:是的
};
this.get=this.get.bind(this)
this.handleScroll=this.handleScroll.bind(this)
}
得到(){
this.setState({isLoading:true});
fetch(“/1.1/followers/list.json?user_id=“+id+”&cursor=“+cursor+”{
标题:{
“授权”:“MyToken”,
}
}).then(response=>response.json())
。然后(数据=>{
if(data.next_cursor==0){
this.setState({isLoading:false})
this.setState({over:true})
}否则{
this.setState({hits:this.state.hits.concat(data.users),isLoading:false})
cursor=data.next\u cursor
console.log(data.next\u游标)
}
}).catch(错误=>{
返回
})
}
componentDidMount(){
这个
window.addEventListener('scroll',this.handleScroll);
}
组件将卸载(){
window.removeEventListener('scroll',this.handleScroll);
}
handleScroll(活动){
if((window.innerHeight+window.scrollY)>=document.body.offsetHeight){
这个
}

}
由于事件似乎被窗口/滚动条多次触发,您需要防止代码中出现重复调用。根据上下文和需求,有很多方法可以做到这一点。这里有几个选择

你可以。如果您只需要确保它在某个时间窗口内只被调用一次,这将是很好的

另一个选项是使用
状态
,以及您已经定义的
isLoading
属性:

get(){
    if(!this.state.isLoading){

       //use the setState callback param here so we don't run into async issues
       this.setState({isLoading: true}, () => {

          ... the rest of your logic ...

          //get is finished (either success or failure)
          this.setState({isLoading: false});
       }
    }
}

使用onScrollBeginDrag怎么样?@Yossi我以前从未听说过它。我不确定它是否已经到期。我将在ScrollBeginDrag上搜索。您是否尝试过在
this.get()之前使用断点或console.log来确定
handleScroll
中发生了什么?我的猜测是,您从窗口中获得了多个符合条件的滚动事件。我不是滚动条方面的专家,但如果当你到达页面底部时事件被多次触发(事件循环比人类的反应快得多),我不会感到惊讶。@BrianS是的,你是对的
useBottomScrollListener(console.log('asd'))
handleScroll
上工作了两次。你知道我怎么能只工作一次吗?