【发布时间】:2021-08-04 09:15:59
【问题描述】:
我在 React 类组件中定义一个方法如下
onSaveAudio = (e) => {
e.preventDefault();
const { audioBlob } = this.state;
let reader = new FileReader();
reader.onloadend = function () {
const base64 = reader.result;
const bstr = base64.split(',')[1];
console.log(bstr);
console.log('this.props', this.props);
this.props.onSaveAudio(bstr);
}
reader.readAsDataURL(audioBlob);
}
在console.log('this.props', this.props) 行,它正在打印“未定义”;在this.props.onSaveAudio 行,抛出错误:
未捕获的类型错误:无法读取未定义的属性“onSaveAudio” FileReader.reader.onloadend (recorder.js:300)
我的理解是“阅读器”读完“audioBlob”后触发“onloadend”。我需要在“onloadend”函数中调用this.props.onSaveAudio,因为如果我在“onloadend”之外调用它,我无法在阅读完成并且“reader.result”准备好和“bstr”后调用" 会以错误的时间解决 undefined ;但如果我在“onloadend”中调用this.props.onSaveAudio,则无法识别“this”。似乎进退两难。
我的猜测是我需要一个解决方案来在“onloadend”中绑定“this”,或者能够在“onloadend”函数完成执行后以某种方式在“onloadend”函数之外计时this.props.onSaveAudio调用。
有什么建议吗?
【问题讨论】:
标签: javascript reactjs