我有一个 this.state,我需要通过 setState 传入我的 componentDidMount,如何在 setState 中使用 bind(this)?
I have one this.state and i need pass in my componentDidMount with setState, how use bind(this) in setState?
我在setState中有那个pass Bind,怎么办?
enter image description here
TypeError: 无法读取未定义的 属性 '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>);
}
}
TypeError: 无法读取未定义的 属性 'setState'
您可以通过两种方式解决 setState undefined 问题
将函数更改为箭头函数
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));
}
我在setState中有那个pass Bind,怎么办? enter image description here
TypeError: 无法读取未定义的 属性 '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>);
}
}
TypeError: 无法读取未定义的 属性 'setState'
您可以通过两种方式解决 setState undefined 问题
将函数更改为箭头函数
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)); }