首页 > 解决方案 > 当父组件突然卸载并且无法及时更新状态时,如何停止react-mic的记录器?

问题描述

我正在使用 react-mic,它在将启动/停止道具传递给它时开始/停止录制。它工作正常,但在某些情况下,当用户在记录器打开时单击应用程序中的其他链接时,react-mic 的父组件会突然卸载,我无法按时更新 this.state.record 并且由于 prop 没有传递给 react-mic,所以标签中的录制点仍然打开,所以有人可以建议我如何停止录制或从标签中删除红点?

import { ReactMic } from 'react-mic';

class ParentComponent extends React.Component {

    stopRecording() {

        this.setState({
          record: false,
        });
    }

    render() {

        <ReactMic
            record={this.state.record} // defaults -> false.  Set to 
                                       // true to begin recording
            onStop={this.onStop}       // callback to execute when 
                                       // audio stops recording
            onData={this.onData}
         />
    }
}


无法更新 this.state.record,因为 ParentComponent 突然卸载

标签: reactjs

解决方案


componentWillUnmount生命周期方法中执行此操作:

import { ReactMic } from 'react-mic';

class ParentComponent extends React.Component {

    stopRecording = () => {

        this.setState({
          record: false,
        });
    }

    compoentWillUnmount(){
      this.stopRecording()
    }

    render() {

        <ReactMic
            record={this.state.record} // defaults -> false.  Set to 
                                       // true to begin recording
            onStop={this.onStop}       // callback to execute when 
                                       // audio stops recording
            onData={this.onData}
         />
    }
}

我已将您的函数转换为箭头函数,因为如果您在构造函数中有绑定方法,则不清楚


推荐阅读