本文介绍了我有一个this.state,我需要通过setState传入我的componentDidMount,如何在setState中使用bind(this)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经通过了setState中的绑定,该怎么办?在此处输入图片描述
TypeError:无法读取未定义的属性'setState'
TypeError: Cannot read property 'setState' of undefined
我正在使用RealTime Firebase和ReactJs
I am using the RealTime Firebase and 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>);
}
}
TypeError:无法读取未定义的属性'setState'
TypeError: Cannot read property 'setState' of undefined
推荐答案
您可以通过两种方式解决setState未定义问题
You can resolve setState undefined issue in two ways
-
将功能更改为箭头功能
Change your functions to arrow functions
componentDidMount() {
this.database.once("value", snapshot => {
snapshot.forEach(data => {
this.setState({users: data.val()})
})
});
}
像下面那样绑定每个功能
Bind each function like below
componentDidMount() {
this.database.once("value", function(snapshot) {
snapshot.forEach(function(data) {
this.setState({users: data.val()})
}.bind(this)}
}.bind(this));
}
这篇关于我有一个this.state,我需要通过setState传入我的componentDidMount,如何在setState中使用bind(this)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!