簡體   English   中英

無法讀取未定義的屬性“功能”

[英]Cannot read property 'function' of undefined

我正在嘗試從我的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;        

注意:如果沒有loadDashboardhandleOnSubmit函數就可以正常工作。

另外 ,為什么將loadDashboard(token){..}更改為loadDashboard(token){..} function loadDashboard(token){..}會給我帶來Unexpected token錯誤?

你可以使用箭頭功能有正確的this方面在回調:

.then((response) => {
    var token = response.data.auth_token;
    console.log(token);
    this.loadDashboard(token);
  })

您也可以執行以下操作,但是arrow功能更平滑:

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

最流暢的方法是在定義函數時使用arrow函數:

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

這樣,您就不需要在構造函數中綁定函數,也不需要松散this的上下文。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM