无法读取undefined的属性'function'

noo*_*bie 1 javascript ecmascript-6 reactjs

我试图从我的React应用程序中的另一个函数调用一个函数.但我保留这个错误:Error in login TypeError: Cannot read property 'loadDashboard' of undefined.我搜索了类似的案例我能找到的是(1)我必须使用this关键字(2)我必须提到里面的功能constructor.我做了两个然后为什么我一直得到错误?
我的代码:

import React, { Component } from 'react';
import '../App.css';
var axios = require('axios');

class Login extends Component {
  constructor(){
    super();
    this.loadDashboard = this.loadDashboard.bind(this);
  }

  loadDashboard(token){
    axios({
      method:'get',
      url:'http://localhost:3000/api/dashboard',
      data: {
        Authorization: token
      },
      responseType:'stream'
    })
     .then(function (response) {
       console.log(response);
     })
     .catch(function (error) {
       console.log("Error in loading Dashboard "+error);
     });
  }

  handleOnSubmit = () => {
     console.log("submittwed");
     axios({
       method:'post',
       url:'http://localhost:3000/authenticate',
       data: {
         email: 'test@mail.com',
         password: 'apple'
       },
     })
      .then(function (response) {
        var token = response.data.auth_token;
        console.log(token);
        this.loadDashboard(token);
      })
      .catch(function (error) {
        console.log("Error in login "+error);
      });
   }

  render() {
    return (
      <div>
         Username: <input type="email" name="fname" /><br />
         Password: <input type="password" name="lname" /><br />
         <button onClick={this.handleOnSubmit}>LOG IN</button>
      </div>
    );
  }
}

export default Login;        
Run Code Online (Sandbox Code Playgroud)

注意:没有loadDashboard,handleOnSubmit功能工作正常.

此外,为什么改变loadDashboard(token){..}function loadDashboard(token){..}让我Unexpected token错误?

use*_*818 5

你可以使用箭头函数this在回调中拥有正确的上下文:

.then((response) => {
    var token = response.data.auth_token;
    console.log(token);
    this.loadDashboard(token);
  })
Run Code Online (Sandbox Code Playgroud)

你也可以这样做,但arrow功能更顺畅:

axios.get("/yourURL").then(function(response) {
  this.setState({ events: response.data });
}.bind(this));
Run Code Online (Sandbox Code Playgroud)