【问题标题】:axios.then(res => { console.log(this) }) prints undefinedaxios.then(res => { console.log(this) }) 打印未定义
【发布时间】:2019-05-19 22:08:02
【问题描述】:

我正在尝试在 axios 调用后设置状态。在 then 子句中,我一直在尝试使用 this.setState({...}) 设置状态,但此处未定义。

为什么console.log(this) 在控制台中打印“未定义”?

  clickButton() {
    let data = {
      username : document.querySelector('#email').value,
      password : document.querySelector('#password').value
    };

    axios.post('http://127.0.0.1:8000/api/login_check', data, {
      headers: {
        'Content-Type' : 'application/json',
      }
    })
    .then(res => {
      console.log(this)
    })
  }

【问题讨论】:

标签: javascript reactjs axios


【解决方案1】:

最明显的原因是因为您的 clickButton 函数不是箭头函数,您一定忘记在构造函数中绑定您的函数。或者,将 clickButton 切换为箭头功能,您应该没问题。

【讨论】:

    【解决方案2】:

    试试下面的代码把 this 绑定到点击按钮函数

    点击按钮 = () => { …… }

    【讨论】:

      猜你喜欢
      • 2018-12-21
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      相关资源
      最近更新 更多