如何从另一个函数调用函数?
问题描述:
我有两个不同的谷歌分析功能。我想从另一个函数调用一个函数。我收到一个错误,说TypeError: this is undefined
。我不明白为什么?如何从另一个函数调用函数?
handleAccounts = (response) => {
var details = response.result.items;
console.log(response);
this.setState({
info: details
});
details.map(function(x) {
gapi.client.analytics.management.webproperties
.list({accountId: x})
.then(this.handleProperties.bind(this)); //This is the line where I am getting the Error.
});
}
handleProperties = (response) => {
// Handles the response from the webproperties list method.
if (response.result.items && response.result.items.length) {
// Get the first Google Analytics account
var firstAccountId = response.result.items[0].accountId;
// Get the first property ID
var firstPropertyId = response.result.items[0].id;
// Query for Views (Profiles).
//queryProfiles(firstAccountId, firstPropertyId);
console.log(response);
} else {
console.log('No properties found for this user.');
}
}
答
如果这些功能正在从一个组件中调用,那么你需要的组件constructor
或componentDidMount
内bind
他们。绑定对于使'this'在回调中起作用是必要的,因为类方法在React中并未默认绑定。
尝试更改'details.map(函数(x){'到'details.map(x => {' –
您必须将“this”绑定到您的箭头函数,箭头函数不会自动假设“this” – darham
它现在正在工作。Thanx很多:) – Parth