【发布时间】:2019-02-06 15:59:26
【问题描述】:
我尝试将状态播放从 false 更改为 true 并尝试添加 ComponentDidMount、ComponentDidUpdate、ComponentWillMount 但没有任何效果。我总是在某个时候收到错误。
点击播放和暂停按钮时效果很好,但我希望它在有人访问该网站时在 2 秒后自动播放。
我的代码:
import React from "react";
class Music extends React.Component {
constructor(props) {
super(props);
this.state = { play: false };
this.url = "http://streaming.tdiradio.com:8000/house.mp3";
this.audio = new Audio(this.url);
this.togglePlay = this.togglePlay.bind(this);
}
// componentDidMount = () => {
// this.togglePlay();
// };
componentDidMount = () => {
setTimeout(this.setState(this.togglePlay()), 500);
};
togglePlay() {
this.setState({ play: !this.state.play });
console.log(this.audio);
this.state.play ? this.audio.play() : this.audio.pause();
}
render() {
return (
<div>
<button onClick={this.togglePlay}>
{this.state.play ? "Pause" : "Play"}
{/* {this.state.play ? "Play" : "Pause"} */}
</button>
</div>
);
}
}
export default Music;
错误:
index.js:1582 Uncaught Error: The error you provided does not contain a stack trace.
at B (index.js:1582)
at G (index.js:1899)
at index.js:1914
at index.js:1933
at index.js:1414
B @ index.js:1582
G @ index.js:1899
(anonymous) @ index.js:1914
(anonymous) @ index.js:1933
(anonymous) @ index.js:1414
music.js:22 Uncaught (in promise) DOMException
togglePlay @ music.js:22
Music._this.componentDidMount @ music.js:16
commitLifeCycles @ react-dom.development.js:16998
commitAllLifeCycles @ react-dom.development.js:18512
callCallback @ react-dom.development.js:147
invokeGuardedCallbackDev @ react-dom.development.js:196
invokeGuardedCallback @ react-dom.development.js:250
commitRoot @ react-dom.development.js:18717
completeRoot @ react-dom.development.js:20247
performWorkOnRoot @ react-dom.development.js:20170
performWork @ react-dom.development.js:20075
performSyncWork @ react-dom.development.js:20049
requestWork @ react-dom.development.js:19904
scheduleWork @ react-dom.development.js:19711
scheduleRootUpdate @ react-dom.development.js:20415
updateContainerAtExpirationTime @ react-dom.development.js:20441
updateContainer @ react-dom.development.js:20509
push../node_modules/react-dom/cjs/react-dom.development.js.ReactRoot.render @ react-dom.development.js:20820
(anonymous) @ react-dom.development.js:20974
unbatchedUpdates @ react-dom.development.js:20292
legacyRenderSubtreeIntoContainer @ react-dom.development.js:20970
render @ react-dom.development.js:21037
./src/index.js @ index.js:16
__webpack_require__ @ bootstrap:782
fn @ bootstrap:150
0 @ routes.js:17
__webpack_require__ @ bootstrap:782
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.chunk.js:1
【问题讨论】:
-
为什么要在 setState() 中调用 togglePlay。你应该像往常一样称呼它
-
请不要:如果用户表示他们想听音乐,就开始播放音乐。不要劫持他人的音频。
标签: javascript reactjs jsx