javascript - 'this' 未定义 - ReactJS
问题描述
我正在构建一个reactJS
代码,即以下代码。它一直在工作,直到我将this.requestCSVDownload()
函数调用添加到我的then
函数中。
async handleMerging(){
console.log("merging launched...")
this.launchMerging({
userId: this.state.userId,
noteId: this.state.noteId,
type: this.state.type,
dateUser: this.state.content
});
var intervalId = await setInterval(()=> {
this.requestPercentage({
userId: this.state.userId,
noteId: this.state.noteId
}).then(async result => {
try{
if(result.hasOwnProperty('Item') &&
result['Item'].hasOwnProperty('mergingProgress') &&
result['Item']['mergingProgress'].hasOwnProperty('N') &&
result['Item']['mergingProgress']['N'] !== null){
var percentage = parseInt(result['Item']['mergingProgress']['N']);
this.setState({
progressMerging: percentage
});
if(percentage === 100){
var result = await this.requestCSVDownloadURL({
userId: this.state.userId,
noteId: this.state.noteId
});
var csvFileURL = await Storage.vault.get(JSON.parse(result.Payload).body.replace("\"", "").replace("\"", ""));
this.setState({
csvFileURL
});
console.log(this.state.csvFileURL)
clearInterval(intervalId)
return;
}
}
}
catch(e){
alert("An error occured...\nConvertion started, just wait a few minutes to see it appear..." + e);
}
});
}, 1500);
}
但它告诉我this is undefined
。
我认为这是我的then
函数
,我尝试添加.bind(this)
以将上下文绑定到我的函数,但没有任何改变。有任何想法吗 ?
解决方案
您到处都有箭头函数,因此上下文来自 function handleMerging()
。如果您像这样调用该函数,则this
上下文将是未定义的(如果使用严格模式)或窗口对象。您将需要向该函数添加绑定,但仅在从对象调用时才使用 handleMerging.bind(this) (或者正如您从 React 组件中所说,但它需要是类而不是函数 - 简单组件 - 因为它没有this
上下文)。
foo.x = function() {
y.addEventListener('click', handleMerging.bind(this));
};
或与组件:
class C extends ReactComponent {
constructor() {
var handleMerging = handleMerging.bind(this);
handleMerging().then(...);
}
}
但这需要从真实的对象上下文中调用,因此在方法内部,如果在函数/方法外部调用它没有任何意义,因为即使您使用绑定,这也将是未定义的。
推荐阅读
- docker - `docker build` 命令挂了很长时间,其他命令工作正常
- postgresql - 当 Google Cloud SQL postgres 服务器升级(到更大的机器)花费的时间比“几分钟”长得多时该怎么办?
- python-3.x - 覆盖范围:编译指示:没有带有多行语句的分支
- java - 我在 JPA 中需要这个 SQL 语句
- chart.js - 页面结构中的响应式 ChartJS
- android - 一旦应用程序启动,如何从结构帐户中永久删除应用程序,因为它使用提供的帐户重新初始化?
- java - Jackson 序列化自定义 TreeNode 对象以返回 JSONObject
- ios - 如何使用 Google Apps 在 Google 表单上请求数字键盘?
- python - #noqa 仅适用于一行导入,但不适用于 import()
- swift - 为什么要忽略我的 tableview 显示搜索结果?