当我在我的 componentDidMount 方法中使用它时,我得到一个 TypeError: this is undefined,即使我相信我绑定(bind)了该方法。我是否错误地绑定(bind)了方法或者是否存在其他问题?我尝试同时使用箭头函数并将其绑定(bind)到构造函数中,但我遇到了同样的错误。
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 (...)}}```
最佳答案
我认为您做错了,因为您在 componentDidMount ( React 的生命周期钩子(Hook)方法)中使用了箭头函数。所以你不再需要这行代码了
this.componentDidMount = this.componentDidMount.bind(this); // remove this one
默认情况下 React 的生命周期钩子(Hook)像 componentDidMount 已经有这个上下文。所以你需要把你的代码改成这个。
componentDidMount() {
}
所以要清楚如果你使用箭头函数不需要使用 bind(this)
关于javascript - componentDidMount() 中的 "This is undefined"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56160541/