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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42650102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:19:24  来源:igfitidea点击:

React. this.setState is not a function inside setTimeout

javascriptreactjs

提问by volna

Current component has state.breakervalue of false. When the scroll event is captured it looks at the stateand if its falseit does some stuff.

当前组件的state.breaker值为 false。当滚动事件被捕获时,它会查看statefalse是否做了一些事情。

I would like to have some kind of static delay before the action will recur and that's why inside goTofunction the state.breakeris set to trueand will block the the further logic of current method for next 2suntil setTimeoutwill return back to false.

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

But at the current moment the following error occurs Uncaught TypeError: this.setState is not a functionwhen setStateis called inside setTimeout.

但是目前出现以下错误Uncaught TypeError: this.setState is not a functionwhen in callsetStateinside 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

}

回答by dfsq

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 windowinside, unless you explicitly bind it with Function.prototype.bind. So here is another way to solve this problem:

请记住,匿名函数window内部会有上下文,除非您明确地将其与Function.prototype.bind绑定。所以这是解决这个问题的另一种方法:

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