【发布时间】:2020-01-16 18:49:56
【问题描述】:
不知道我做错了什么。我知道我无法访问正确的 this,但我认为使用箭头函数可以解决这个问题。我的console.log(this) 返回未定义。
handleSubmit(event) {
event.preventDefault();
const formData = {
username: event.target.username.value,
password: event.target.password.value
}
fetch('http://localhost:4000/user/login', {
method: "POST",
mode: "cors",
body: JSON.stringify(formData),
headers: {
"Content-Type": "application/json"
}
})
.then((res) => res.json())
.then((res) => {
if(res.token == undefined) {
console.log(this)
this.setState({ logFailureMsg: res.message })
} else {
localStorage.setItem('authorization', `Bearer ${res.token}`);
}
})
.catch(err => console.error(err))
}
【问题讨论】:
-
你调试错了地方,它不在
this未定义的承诺回调中,它在整个handleSubmit函数中,因为你可能没有绑定它,也不是箭头函数类成员。 -
是的,这是正确的,实际上为我解决了很多困惑。
-
JS 中的上下文不是一个微不足道的概念,它在某些时候会妨碍每个开发人员。每当上下文在某处变得未定义时,请扩大范围并确保上下文是您所期望的。这是调试此类问题的良好第一步。 ;)
标签: javascript reactjs scope this