[英]React Cannot read property setState of undefined in .then() even using arrow function
Not sure what I'm doing wrong.不知道我做错了什么。 I know that I'm not able to access the proper this, but I thought using arrow function resolves that.
我知道我无法访问正确的 this,但我认为使用箭头函数可以解决这个问题。 my
console.log(this)
returns undefined.我的
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 is not an arrow function.这不是箭头函数。 Change your function to look like this:
将您的函数更改为如下所示:
handleSubmit = event => {
// your code...
}
Also, remember to call your function as this.handleSubmit
, otherwise this
will not be bound.另外,请记住将您的函数调用为
this.handleSubmit
,否则this
将不会被绑定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.