反应.this.setState不是setTimeout中的函数

vol*_*lna 17 javascript reactjs

当前组件的state.breaker值为false.当捕获滚动事件时,它会查看statefalse是否会执行某些操作.

我希望在动作重现之前有某种静态延迟,这就是为什么内部goTo函数state.breaker设置为true并将阻止当前方法的进一步逻辑,2s直到setTimeout将返回到false.

但是在当前时刻发生以下错误Uncaught TypeError:this.setStatesetState内部调用不是函数setTimeout.

class Slide extends Component {
  constructor(props) {
    super(props)

    this.state = {
      breaker: false
    }

    this.scrollRedirect = this.scrollRedirect.bind(this);
  }

  componentDidMount() {
    this.refs.holder.addEventListener('mousewheel', this.scrollRedirect);
  }


  scrollRedirect(e) {

    const path = this.props.location.pathname,
    goTo = (route) => {
      this.setState({breaker: true});
      hashHistory.push(route);

      setTimeout(function () {
        this.setState({breaker: false});
      }, 2000)
    };

    if (!this.state.breaker) {
       ... code that executes goTo on condition
    }
  }

  ... render code

}
Run Code Online (Sandbox Code Playgroud)

dfs*_*fsq 75

你正在失去背景.使用箭头函数作为保存正确执行上下文的简单方法:

setTimeout(() => {
  this.setState({breaker: false});
}, 2000)
Run Code Online (Sandbox Code Playgroud)

请记住,匿名函数将在其中包含上下文window,除非您使用Function.prototype.bind显式绑定它.所以这是解决这个问题的另一种方法:

setTimeout(function () {
  this.setState({breaker: false});
}.bind(this), 2000)
Run Code Online (Sandbox Code Playgroud)

  • 祝福箭头功能:) (4认同)