【问题标题】:React. this.setState is not a function inside setTimeout [duplicate]做出反应。 this.setState 不是 setTimeout 中的函数 [重复]
【发布时间】:2017-07-27 18:25:28
【问题描述】:

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

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

但目前在setState 内部调用setTimeout 时出现以下错误Uncaught TypeError: this.setState is not a function

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

}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 真的,谢谢! :)
    • 祝福箭头函数 :)
    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 2016-01-27
    • 2015-08-06
    • 2015-09-11
    • 1970-01-01
    • 2019-05-01
    相关资源
    最近更新 更多