小编典典

反应 this.setState不是setTimeout内部的函数

reactjs

当前组件的state.breaker值为false。捕获滚动​​事件时,它会查看,state如果有,它false会做一些事情。

我想在动作再次发生之前有某种静态延迟,这就是为什么将内部goTo函数state.breaker设置为true并将阻塞当前方法的进一步逻辑的原因,2s直到setTimeout返回到false

但在当前时刻出现以下错误 遗漏的类型错误:this.setState不是一个函数setState被内部调用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

}

阅读 250

收藏
2020-07-22

共1个答案

小编典典

您正在失去上下文。使用箭头功能作为保留适当执行上下文的简单方法:

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

请记住window,除非您将匿名函数与Function.prototype.bind明确绑定,否则匿名函数将在内部具有上下文。因此,这是解决此问题的另一种方法:

setTimeout(function () {
  this.setState({breaker: false});
}.bind(this), 2000)
2020-07-22