ReactJS中componentWillMount内调用setState()报错的解决方法
解决React中
this.setState is not a function的问题 嘿,刚遇到这个问题的时候我也懵过,别担心,这是React里很常见的this指向问题~
问题原因
你在onAuthStateChanged里用了普通的function作为回调,这个时候函数内部的this已经不是你的React组件实例了,而是指向调用这个回调的上下文(这里是Firebase的内部上下文),所以自然找不到setState方法啦。
三种解决方案,选你顺手的来:
1. 改用箭头函数(最推荐)
箭头函数不会创建自己的this,它会继承外层作用域的this(也就是你的组件实例),直接就能正常调用setState:
componentWillMount() { var config = {...}; Firebase.initializeApp(config) Firebase.auth().onAuthStateChanged((user) => { if(user){ console.log("User logined"); this.setState({ isLogined : true }) }else{ console.log("User isn't logined"); this.setState({ isLogined : false }) } }) }
2. 提前保存this的引用
在回调函数外面把组件的this存到一个变量里(比如that),然后在回调里用这个变量代替this:
componentWillMount() { var config = {...}; Firebase.initializeApp(config) const that = this; Firebase.auth().onAuthStateChanged(function(user){ if(user){ console.log("User logined"); that.setState({ isLogined : true }) }else{ console.log("User isn't logined"); that.setState({ isLogined : false }) } }) }
3. 用bind绑定this
把回调函数的this手动绑定到组件实例上,也能修正指向问题:
componentWillMount() { var config = {...}; Firebase.initializeApp(config) Firebase.auth().onAuthStateChanged(function(user){ if(user){ console.log("User logined"); this.setState({ isLogined : true }) }else{ console.log("User isn't logined"); this.setState({ isLogined : false }) } }.bind(this)) }
另外提一句,现在React官方已经不推荐使用componentWillMount啦,建议换成componentDidMount或者在函数组件里用useEffect,不过先解决眼前的报错更重要~
内容的提问来源于stack exchange,提问作者Bucky
相关产品推荐
相关产品推荐

