我在我的React组件中使用onscroll事件,如下所示:
import React, { Component } from 'react';
import throttle from 'lodash/throttle';
class Example extends Component {
state = {
navigationFixed: false,
}
componentDidMount() {
window.addEventListener('scroll', this.throttledHandleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.throttledHandleScroll);
}
handleScroll = () => {
this.contentRef && this.setState({
navigationFixed: window.scrollY >= this.contentRef.offsetTop - 32,
});
throttledHandleScroll = throttle(this.handleScroll, 80); // Using lodash throttle here
render() {
//Some variables and components here
...
<section
className={cx(s.content, {
[s.navigationFixed]: this.state.navigationFixed,
})}
id="content"
ref={(ref) => {this.contentRef = ref}}
>
...
//Another components here
</section>
}
};
这个工作正常,但有时会冻结,我想这是因为handleScroll函数,它经常触发。所以我的问题是如何优化此代码?
答案 0 :(得分:2)
尝试对handleScroll
方法进行此修改。
handleScroll = () => {
if(!this.contentRef) return;
const navShouldBeFixed = window.scrollY >= this.contentRef.offsetTop - 32
if(this.state.navigationFixed && !navShouldBeFixed) {
this.setState({navigationFixed: false});
} else if (!this.state.navigationFixed && navShouldBeFixed) {
this.setState({navShouldBeFixed: true})
}
}
编辑:减少代码行。
handleScroll = () => {
if(!this.contentRef) return;
const navShouldBeFixed = window.scrollY >= this.contentRef.offsetTop - 32
if(this.state.navigationFixed && !navShouldBeFixed ||
!this.state.navigationFixed && navShouldBeFixed) {
this.setState({navigationFixed: navShouldBeFixed});
}
}
这样,只有在UI需要更改时才会触发setState
方法。