我有一个构造函数、get 方法、componentDidMount 和 componentWillUnmount 方法。我只想监听滚动事件,然后根据该事件调用 get 方法。如果滚动到页面底部,则调用一次 get 方法。就这样。第一个调用,即 componentDidmount(),运行了一次,但是当我向下滚动时,get 方法运行了两次。我不希望它执行多次。
这是我的代码:
constructor(props) {
super(props);
cursor = -1
id = auth().currentUser.providerData[0].uid
this.state = {
hits: [],
isLoading: false,
over: false,
firstCall: true
};
this.get = this.get.bind(this)
this.handleScroll = this.handleScroll.bind(this)
}
get() {
this.setState({ isLoading: true });
fetch("/1.1/followers/list.json?user_id=" + id + "&cursor=" + cursor + "", {
headers: {
'Authorization': 'MyToken',
}
}).then(response => response.json())
.then(data => {
if (data.next_cursor == 0) {
this.setState({ isLoading: false })
this.setState({ over: true })
} else {
this.setState({ hits: this.state.hits.concat(data.users), isLoading: false })
cursor = data.next_cursor
console.log(data.next_cursor)
}
}).catch(error => {
return
})
}
componentDidMount() {
this.get()
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll(event) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
this.get()
}
}
这是我的控制台输出。
1634251341094964000 ----> 一次
1614497980820334000 ---->两次
1579177573029464600 ---->两次
。 。 .
它们来自 get 函数中的 console.log(data.next_cursor)。
最佳答案
由于窗口/滚动条似乎多次触发该事件,因此您需要防止代码中的重复调用。有很多方法可以做到这一点,具体取决于上下文和要求。这里有几个选项。
你可以debounce the function call 。如果您只需要确保它只在特定时间窗口内调用一次,这会很好。
另一种选择是使用 state
以及您已经定义的 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});
}
}
}
关于javascript - 为什么我的函数无意中执行了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59801559/