美文网首页React Native开发经验集
关于this.setState is not a functio

关于this.setState is not a functio

作者: 繁华遇见 | 来源:发表于2018-10-07 22:09 被阅读13次

写项目的时候在实现组件内部功能的时候,用到了React的状态管理。然后报了个错。


报错.png

代码如下

componentDidMount() {
        window.onscroll = function () {
            let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            let clientHeight = document.documentElement.clientHeight;
            let style = scrollTop > clientHeight ? 'backTop show' : 'backTop';
            this.setState({ backStyle: style });
        }
    }

一打眼看真的没啥问题,没写成赋值的形式,也没多点啥,也没少点啥。
上网上一查,傻眼了。一定要注意this的作用域。
帮助解决的网站:# 倒计时功能,用setInterval设置每秒重设状态,报错this.setState is not a function

看一下this吧,打印出来:

componentDidMount() {
        window.onscroll = function () {
            let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            let clientHeight = document.documentElement.clientHeight;
            // let style = scrollTop > clientHeight ? 'backTop show' : 'backTop';
            // this.setState({ backStyle: style });
            console.log('window this:',this);
        }
        console.log('react this:',this);
    }

结果明显:


打印结果.png

Window对象里必然是没有setState方法的啊。果然是太不仔细了。这种低级错误。

解决方式就是:
1、使用ES6 箭头函数。
2、不是用箭头函数,在函数结尾 .bind(this)

总结起来就是,在React中尽量使用箭头函数,毕竟React本身就主要使用ES6 的语法。

相关文章

网友评论

    本文标题:关于this.setState is not a functio

    本文链接:https://www.haomeiwen.com/subject/cquraftx.html