反应:setState在滚动处理程序中返回错误。是什么在破坏它?

时间:2018-12-25 04:16:35

标签: javascript reactjs state

当用户到达页面底部然后向上滚动时,React引发错误“ TypeError:_this.setState不是函数”

这是一个滚动处理程序,用于检查客户端的位置。如果客户端位于页面的主页部分,它将更新状态{active:'home'}。然后,导航栏组件重新渲染,并为home-navlink分配活动类。

class Navbar extends Component {

  constructor(){

    super();

    this.state = {

    active: 'home'

    };

    this.handleScroll = this.handleScroll.bind(this);


  }

  componentDidMount(){

    document.addEventListener('scroll', this.handleScroll);

  }

 componentWillUnmount(){

    document.removeEventListener('scroll', this.handleScroll);

  }



  //offset values are location of elements minus the navbar (10vh)

  handleScroll = ()=>{

    let wind = window.pageYOffset;

    let tenVh = window.innerHeight / 10;

    let offset = {

      home: document.getElementById('home').offsetTop - tenVh,

      tech: document.getElementById('tech').offsetTop - tenVh,

      projects: document.getElementById('projects').offsetTop - tenVh,

      contact: document.getElementById('contact').offsetTop - tenVh,

    };

    if (wind < offset.tech){

      if (this.state.active !== 'home' ){ 

        this.setState({

          active: 'home'

        });

      }

    } else if (wind > offset.tech && wind < offset.projects){

      if (this.state.active !== 'tech' ){

        this.setState({

          active: 'tech'

        });

      }

    } else if ( wind > offset.projects && wind < offset.contact ){

      if (this.state.active !== 'projects' ){

        this.setState({

          active: 'projects'

        });

        }

    } else if (wind > offset.contact){

      if (this.state.active !== 'contact' ){

        this.setState = ({

          active: 'contact'

        });

      }

    }

    }

    render(){   

    return(

      <div className="navbar" >

        <div className="navbrand">  

        <a href="#home">

          <img src={brand} alt='pig brand' />

          LtP</a>

        </div>

        <div className="link-ctr">

            <a href="#home" className={

              (this.state.active ==='home')?'active':null}>Home</a>

            <a href="#tech" className={

              (this.state.active === 'tech')?'active':null}>Tech</a>

            <a href="#projects" className={

              (this.state.active === 'projects')?'active':null}>Projects</a>

            <a href="#contact" className={

              (this.state.active === 'contact')?'active':null}>Contact</a>

        </div>

    </div>
    )
    }
    }

1 个答案:

答案 0 :(得分:1)

更改

this.setState = ({
      active: 'contact'
});

收件人

 this.setState({
     active: 'contact'
 });

构造函数中也不需要以下内容,因为handleScroll是一个箭头函数,因此箭头函数不需要手动绑定

  this.handleScroll = this.handleScroll.bind(this);