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

问题描述 投票:0回答:1

不确定我在做什么错。我知道我无法访问正确的设置,但是我认为使用箭头功能可以解决该问题。我的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)) 
}
javascript reactjs scope this
1个回答
2
投票

这不是箭头功能。更改功能,使其看起来像这样:

handleSubmit = event => {
    // your code...
}

此外,请记住将函数调用为this.handleSubmit,否则将不会绑定this

© www.soinside.com 2019 - 2024. All rights reserved.