reactjs - 当父组件突然卸载并且无法及时更新状态时,如何停止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 突然卸载
解决方案
在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}
/>
}
}
我已将您的函数转换为箭头函数,因为如果您在构造函数中有绑定方法,则不清楚
推荐阅读
- javascript - 如何在不使用 Selenium 和节点 js 刷新页面的情况下重新加载元素?
- php - 运行 laravel 项目 php artisan serve 时出现致命错误
- node-config - node-config 将分隔符从点更改为冒号
- git - Git - 创建 PR 显示较旧的提交
- vue.js - 如何在 Vue CLI 中加载 JSON 而不会出现 CORS 错误
- python - AttributeError:对象没有属性“_output_tensor_cache”
- javascript - Electron / Browser:检测何时从任务栏再次打开应用程序(最小化后)
- node.js - 如何修改 NodeJS 内置的全局对象?
- c++ - 为什么我的代码中的 fprintf() 函数不能正常工作?
- angular - Angular formControl - 在 ngfor 循环的特定行中设置一个值