【问题标题】:ReactJS : this.setState is not a function?ReactJS:this.setState 不是函数吗?
【发布时间】:2016-06-30 13:15:23
【问题描述】:

我是 ReactJS 的新手,我遇到了一个错误“this.setState is not a function”。

constructor() {
    super();

    this.state = {
        visible: false,
        navLinesShow: true
    };

    this.navOpen = this.navOpen.bind(this)

}

navOpen() {
    this.setState({
        navStatus: "navShow",
        navLinesShow: false
    });

    if ( this.state.visible === false) {

        setTimeout(function (){

            this.setState({
                visible: true
             });

        }, 3000);

    }

我已将 this.navOpen = this.navOpen.bind(this) 添加到构造函数中。所以我想问题出在 setTimeout 函数上。

什么是可能的解决方法?

谢谢。

【问题讨论】:

    标签: javascript reactjs setstate


    【解决方案1】:

    是的,问题是 setTimeout 函数中的 setTimeout “this”指的是函数本身:所以解决方案是典型的var that = this

    navOpen() {
    this.setState({
        navStatus: "navShow",
        navLinesShow: false
    });
    if ( this.state.visible === false) {
     var that = this;
        setTimeout(function (){
            that.setState({
                visible: true
             });
        }, 3000);
    }
    

    【讨论】:

    • 你好 Pinturic。是的,这非常有效。也许您可以为我解释一下,以便更好地理解?
    • 您也可以使用箭头函数:setTimeout( _ => { this.setState(...) }, 3000)this 按预期工作
    • 如果不清楚,我会更新解决方案,我会详细说明。如果您的浏览器/转译器支持 @pawel 是正确的,您可以使用粗箭头语法
    • 如果没有转译/ES6 支持,您可以避免 that = this 使用 bind: setTimeout(function(){ ... }.bind(this), 3000) :)
    • Pawel 我猜 .bind(this) 目前最适合我!谢谢
    【解决方案2】:

    这是因为this 由于运行时绑定而没有正确的值。您需要使用词法绑定。最好的解决方案是使用ES6 箭头函数() => {},它提供了这个值的词法绑定。即使使用setTimeout(),它的词法绑定也可以解决您遇到的错误

    constructor() {
        super();
    
        this.state = {
            visible: false,
            navLinesShow: true
        };
    }
    
    navOpen = () => {
        this.setState({
            navStatus: "navShow",
            navLinesShow: false
        });
    
        if ( this.state.visible === false) {
            setTimeout(() => {
                this.setState({
                    visible: true
                 });
            }, 3000);
        }
    }
    

    【讨论】:

      【解决方案3】:

      除了@pinturic 的解决方案之外的另一个解决方案是使用 ES6 箭头函数。如果你使用ES6/Babel等,可以使用箭头函数绑定到词法this

      navOpen() {
          this.setState({
              navStatus: "navShow",
              navLinesShow: false
          });
          if (!this.state.visible) {
              setTimeout(() => this.setState({visible: true}), 3000);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-08-22
        • 2015-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-01
        • 2017-11-11
        • 1970-01-01
        相关资源
        最近更新 更多