【问题标题】:this.setState is not a function, react nativethis.setState 不是函数,反应原生
【发布时间】:2015-08-06 20:44:07
【问题描述】:

我知道有类似的问题,但没有一个可以帮助我解决我的问题。

所以这是我的问题。

我正在使用 react native 并使用通量调度程序。我的应用调度程序的调度和注册工作正常。我的问题是,当我想更改/设置调度寄存器函数中的状态时,我总是收到 this.setState() 不是函数的错误消息。当然我当时认为这一定是一个绑定问题(用 es6 编写),所以我尝试了各种绑定“this”但我仍然无法让它工作。有人知道为什么吗?

下面是那段不起作用的代码:

testDispatcher() {    
    AppDispatcher.register( (action) => {
        if ( action.action === TEST_ACTION ) {
            // I tried setting state inside here
            this.setState({
                view: action.view
            }).bind(this); // with or without this bind doesn't make a difference

            // I also tried having a function outside of this function where I set the state.. this doesn't work either.
            //this.updateView('home').bind(this);
            console.log('dispatch register');
        }
    });
}

我还尝试在我的注册函数中控制台记录“this”,并且“this”确实返回了我的应用程序类。

【问题讨论】:

    标签: javascript reactjs ecmascript-6 flux


    【解决方案1】:

    =>this 绑定到testDispatcher() 的范围。这可能不是你想要的。在这种情况下,我认为您应该放弃 => 符号,而只是一个常规的匿名函数。

    另外,this.setState(...args...).bind(this) 是完全错误的。 1)this.部分表示.bind(this)是多余的。 2) 绑定语法如下:foo.setState.bind(notFoo, ...args...).

    【讨论】:

    • 您好,感谢您的回复。但是我不想将它绑定到我的 testDispatcher 函数中的 AppDispatcher 函数吗?如果我不这样做,我最终会在那里拥有调度程序的对象,然后我也不能使用 this.setState 。这真的很奇怪,因为当我使用箭头函数并记录“this”时,我确实得到了我的 Class,这就是我想要的,但它仍然不允许我使用 this.setState。
    • 我解决了!我没有在我的类中从 React Component 扩展,因此 setState 不是一个函数.. 哦,男孩.. 抱歉,我应该发布更多代码,这样会更明显。
    【解决方案2】:

    我的类没有从 React 组件扩展,因此 this.setState 不是一个函数。

    【讨论】:

    • 遇到了同样的问题。你的回答很有道理!
    • 这样吗?导出默认类 MyWeatherApp 扩展组件
    猜你喜欢
    • 1970-01-01
    • 2015-09-11
    • 2018-02-27
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多