【问题标题】:React Cannot read property setState of undefined in .then() even using arrow function即使使用箭头函数,React 也无法读取 .then() 中未定义的属性 setState
【发布时间】: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


【解决方案1】:

这不是箭头函数。将您的函数更改为如下所示:

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

另外,记得将你的函数调用为this.handleSubmit,否则this将不会被绑定。

【讨论】:

  • 啊。我认为 .then((res) => {} 是我所需要的,但提交函数需要是箭头函数。这非常有用。谢谢。console.log(this) 现在返回正确的对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 2018-12-05
  • 2016-03-03
  • 2020-07-10
  • 2018-02-11
  • 2020-03-05
相关资源
最近更新 更多