我在setState中已经通过Bind了,怎么办? enter image description here
类型错误:无法读取未定义的属性“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()}) }) }); }
像下面这样绑定(bind)每个函数
componentDidMount() { this.database.once("value", function(snapshot) { snapshot.forEach(function(data) { this.setState({users: data.val()}) }.bind(this)} }.bind(this)); }
关于javascript - 我有一个 this.state ,我需要用 setState 传入我的 componentDidMount ,如何在 setState 中使用 bind(this) ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54615829/