React - uncatch TypeError:无法读取未定义的属性(读取'setState')



我无法在回调函数中setState来获取S3上传的进度百分比。

我想做的是从pc中选择一个文件,将其上传到S3,并在我的dom中用进度条进行渲染

class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = { uri: "", uploadProgress : 0 };
}
async onChange(e) {
const file = e.target.files[0];
//upload to S3, works great
try {
await Storage.put(file.name, file, {
progressCallback(progress) {
const prog = parseInt(progress.loaded/progress.total*100)
console.log(prog+"%");
//undefined
this.setState({uploadProgress: prog})
},
contentType: file.type, // contentType is optional
});
} catch (error) {
console.log("Error uploading file: ", error);
}
//get from S3, works but not the setState
try {
const amen = await Storage.get(file.name, { expires: 60 });
this.setState({
uri: amen
})
} catch (error) {
console.log("Error file: ", error);
}
}
render() {
return (
<div>
<input type= "file" onChange = { this.onChange } />
<img src={this.state.uri}/>
{this.state.uploadProgress && <ProgressBar now={this.state.uploadProgress} label={this.state.uploadProgress + "%"} />}
</div>
)
}
}

除此之外一切正常:

this.setState({uploadProgress: prog})

我不明白为什么我不能称我的状态为进步,怎么了?

您正在从不同的执行上下文中调用this关键字。progressCallback中的this在其本地执行上下文中搜索一个名为setState的方法,但找不到它

正如这个相关的答案所描述的那样,您可以通过如下更改代码来引用正确的this


async onChange(e) {
const baseThis = this;
const file = e.target.files[0];
try {

await Storage.put(file.name, file, {
progressCallback(progress) {
const prog = parseInt(progress.loaded/progress.total*100)
console.log(prog+"%");
baseThis.setState({uploadProgress: prog})
},
contentType: file.type, // contentType is optional
});
} catch (error) {
console.log("Error uploading file: ", error);
}

// other things
}

最新更新