我有一個使用https://github.com/selz/plyr媒體播放器的React組件。一切正常,直到組件解除安裝,這會導致Vimeo API發生錯誤。具體來說:Uncaught (in promise) TypeError: Cannot read property 'postMessage' of null
。Vimeo API與ReactJS和Plyr
發生此錯誤後,我嘗試再次加載模塊,它將因this.player
爲undefined
而失敗,但是如果您銷燬它並再次嘗試,將會加載該模塊。也許React樹正在保存組件的第一個迭代,我需要以某種方式徹底銷燬它?
這裏是我的組件:
import React, {Component, PropTypes} from 'react';
import {findDOMNode} from 'react-dom';
import plyr from 'plyr';
/**
* @desc Regex to retrieve the Vimeo video ID from the URL.
* @type {RegExp}
*/
const regex = /^.*(vimeo\.com\/)((channels\/[A-z]+\/)|(groups\/[A-z]+\/videos\/))?([0-9]+)/g;
export default class Vimeo extends Component {
static propTypes = {
url: PropTypes.string.isRequired,
};
constructor(props) {
super(props);
// Use regex to get the video id from the url
this.videoId = regex.exec(this.props.url);
}
/*
|--------------------------------------------------------------------------
| Digest Cycle
|--------------------------------------------------------------------------
*/
/**
* @desc Initiate video player.
*/
componentDidMount() {
this.player = plyr.setup(findDOMNode(this), {
controls: [],
autoplay: true,
loop: true,
mute: true,
});
this.player[0].on('ready',() => {
// Mute the video
if (!this.player[0].isMuted()) {
this.player[0].toggleMute();
}
});
}
/**
* @desc Destroy video player
*/
componentWillUnmount() {
this.player[0].destroy();
}
/*
|--------------------------------------------------------------------------
| Render
|--------------------------------------------------------------------------
*/
render() {
let player = null;
if (typeof this.videoId !== 'undefined' && this.videoId !== null) {
player = (
<div>
<div
data-type="vimeo"
data-video-id={this.videoId}
/>
</div>
);
}
return player;
}
}
@RyanPotter任何更新? :) –