使用react-autoBind时ReactJs setState未定义

时间:2019-01-20 00:02:39

标签: javascript reactjs jsx

获取此未捕获的TypeError:尝试在函数中设置setState时,无法读取未定义的属性“ setState”。我知道已经发布了其他类似的问题,但是它们都没有使用react-autobind

当我在构造函数中绑定函数时,此方法有效:

this.toggleNav = this.toggleNav.bind(this)

但是我想用react-autobind

完成
import React from "react";
import ReactDOM from "react-dom";
import ScrollspyNav from "react-scrollspy-nav";
import autoBind from 'react-autobind';

export default class Navigation extends React.Component {
constructor(props) {
  super(props);
  autoBind(this);

  this.state = {
    toggleMobileNav: false
  };

}

    toggleNav() {
      this.setState((prev, props) => {
        return {
            toggleMobileNav: !prev.toggleMobileNav
        }
      });
    }


render() {
    return(

        <ScrollspyNav
            scrollTargetIds={["page-top", "about", "projects", "signup"]}
            activeNavClass="is-active"
            scrollDuration="1000"
            headerBackground="false"
            activeNavClass="active-nav"
        >

            <nav className="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
              <div className="container">
                <a id="page-top" className="navbar-brand js-scroll-trigger" href="#page-top">Start Bootstrap</a>
                <button className="navbar-toggler navbar-toggler-right" onClick={this.toggleNav} type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
                  Menu &nbsp;&nbsp;
                  <i className="fas fa-bars"></i>
                </button>
                <div className= {this.state.toggleMobileNav ? "show collapse navbar-collapse" : " " + 'collapse navbar-collapse'} id="navbarResponsive">
                  <ul className="navbar-nav ml-auto">
                    <li className="nav-item">
                      <a className="nav-link" href="#about">About</a>
                    </li>
                    <li className="nav-item">
                      <a className="nav-link" href="#projects">Projects</a>
                    </li>
                    <li className="nav-item">
                      <a className="nav-link" href="#signup">Contact</a>
                    </li>
                  </ul>
                </div>
              </div>
            </nav>
        </ScrollspyNav>
)

} }

1 个答案:

答案 0 :(得分:1)

如果使用箭头函数语法声明您的方法,则无需调用this.toggleNav = this.toggleNav.bind(this)或使用react-autobind

toggleNav = () => {
  this.setState((prev, props) => {
    return {
      toggleMobileNav: !prev.toggleMobileNav
    }
  });
}

这是一篇中型文章,涵盖了所有选项:https://medium.com/komenco/react-autobinding-2261a1092849