反应.this.setState不是setTimeout内部的函数 [英] React. this.setState is not a function inside setTimeout

查看:34
本文介绍了反应.this.setState不是setTimeout内部的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前组件的 state.breaker 值为false.捕获滚动​​事件时,它会查看 state 状态,如果其 false ,它将执行某些操作.

Current component has state.breaker value of false. When the scroll event is captured it looks at the state and if its false it does some stuff.

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

I would like to have some kind of static delay before the action will recur and that's why inside goTo function the state.breaker is set to true and will block the the further logic of current method for next 2s until setTimeout will return back to false.

但是目前,发生以下错误 未捕获的TypeError:当在内部调用 setState 时,this.setState不是函数 > setTimeout .

But at the current moment the following error occurs Uncaught TypeError: this.setState is not a function when setState is called inside 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

}

推荐答案

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

You are loosing context. Use arrow function as simple way to preserve proper execution context:

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

请记住,除非您将匿名函数与

Remember that anonymous function will have context window inside, unless you explicitly bind it with Function.prototype.bind. So here is another way to solve this problem:

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

这篇关于反应.this.setState不是setTimeout内部的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆