【问题标题】:React: FileReader onloadend doesn't recognize "this" if defined in a component method反应:如果在组件方法中定义,FileReader onloadend 无法识别“this”
【发布时间】: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


    【解决方案1】:

    我发现的一种方法是在定义“reader.onloadend”时使用箭头函数。

        reader.onloadend = () => {
            const base64 = reader.result;
            const bstr = base64.split(',')[1];
            console.log(bstr);
            console.log('this.props', this.props);
            this.props.onSaveAudio(bstr);
        }
    
    

    this.props 将在这种情况下定义

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 2017-07-03
      相关资源
      最近更新 更多