【发布时间】:2019-10-03 06:12:47
【问题描述】:
当我在 componentDidMount 方法中使用 this 时,我得到一个 TypeError: this is undefined,即使我相信我绑定了该方法。是我错误地绑定了方法还是有其他问题?我尝试使用这两个箭头函数并将其绑定在构造函数中,但我得到了同样的错误。
constructor(...args) {
super(...args);
// this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
email: null,
address: null,
address2: null,
city: null,
state: null,
zip: null,
subscribe: null,
currentUser: null,
displayName: null,
uid: null,
}
this.handleChange = this.handleChange.bind(this);
this.componentDidMount = this.componentDidMount.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount = () => {
firebaseRef.auth().onAuthStateChanged(function(user) {
if (user) {
[...]
})
this.setState({
uid: user.uid,
displayName: user.displayName});
db.collection("testCollection").doc("handleSubmitTest8").set({
// uid:this.state.uid,
test: "testy",
}).then(function() {
console.log("Document written in handleSumit in NUM");
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
} else {
console.log("no user signed in");
}
});
}
handleSubmit = (event) => {
[...]
}
handleChange(event) {
[...]
}
render() {
return (...)}}```
【问题讨论】:
-
你不需要绑定生命周期方法
-
从构造函数中删除这一行,你就可以开始了。 this.componentDidMount = this.componentDidMount.bind(this);
标签: javascript node.js reactjs ecmascript-6