我在setState中已经通过Bind了,怎么办?
在此输入图像描述 https://i.stack.imgur.com/hkneq.png
类型错误:无法读取未定义的属性“setState”
我正在使用 RealTime Firebase 和 ReactJs
constructor() {
super()
this.app = firebase.initializeApp(firebase_config);
this.database = this.app.database().ref().child('users');
this.state = {
users: []
}
}
componentDidMount() {
this.database.once("value", function(snapshot) {
snapshot.forEach(function(data) {
this.setState({users: data.val()})
})
});
}
render() {
return (
<BrowserRouter>
<div className="App">
<Navbar/>
<Switch>
<Route exact="exact" path='/' component={CampaingListClients}/>
</Switch>
<p>{this.state.users}</p>
</div>
</BrowserRouter>);
}
}
类型错误:无法读取未定义的属性“setState”
您可以通过两种方式解决 setState 未定义问题
-
将您的函数更改为箭头函数
componentDidMount() {
this.database.once("value", snapshot => {
snapshot.forEach(data => {
this.setState({users: data.val()})
})
});
}
-
如下所示绑定每个函数
componentDidMount() {
this.database.once("value", function(snapshot) {
snapshot.forEach(function(data) {
this.setState({users: data.val()})
}.bind(this)}
}.bind(this));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)