[英]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;
注意:如果沒有loadDashboard
, handleOnSubmit
函數就可以正常工作。
另外 ,為什么將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.