简体   繁体   English

即使使用箭头函数,React 也无法读取 .then() 中未定义的属性 setState

[英]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.

相关问题 ReactJS TypeError:即使在构造函数中绑定并使用箭头 function 后,也无法读取未定义的属性“setState” - ReactJS TypeError: Cannot read property 'setState' of undefined even after binding in the constructor and also using the arrow function React - TypeError:无法读取未定义的属性“setState”(箭头函数) - React - TypeError: Cannot read property 'setState' of undefined (Arrow functions) 无法读取未定义的属性“setState” - 转换为箭头 function - Cannot read property 'setState' of undefined - Converted to arrow function 无法读取未定义REACT的setState属性 - Cannot read property of setState of undefined REACT 在反应中无法读取未定义的属性“ setState” - In react Cannot read property 'setState' of undefined React Hooks“无法读取未定义的属性'setState'” - React Hooks “Cannot read property 'setState' of undefined” 反应:无法读取未定义的属性“setState” - React: Cannot read property 'setState' of undefined React-无法读取undefined的属性'setState' - React- Cannot read property 'setState' of undefined React - TypeError:无法读取未定义的属性“setState” - React - TypeError: Cannot read property 'setState' of undefined 反应错误 - 无法读取未定义的属性“setState” - React error - Cannot read property 'setState' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM