2017-09-07 30 views
0

我正在使用這個hls.js player以及React流m3u8。我有一個組件VideoPlayer,它設置了hls.js播放器。該組件有幾個狀態屬性,如isPlayingisMuted。我有自定義按鈕onClick調用組件函數setState,但這當然重新呈現組件和視頻流重新裝入我猜,並回到它的原始狀態,這是它回到它的第一幀並停止。一般來說,您如何處理應用程序(redux)或流式視頻的本地狀態更改?我注意到,無論任何時候redux商店更新或本地狀態更改,視頻總是會有「閃爍」(這是重新呈現)。如何使用http直播HLS處理React生命週期?

的代碼示例更新:

import React, {PropTypes} from 'react'; 
import Hls from 'hls.js'; 

class VideoPlayer extends React.Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     isMuted: true, 
     isPlaying: false, 
     playerId : Date.now() 
    }; 

    this.hls = null; 
    this.playVideo = this.playVideo.bind(this); 
    } 

    componentDidMount() { 
    this._initPlayer(); 
    } 

    componentDidUpdate() { 
    this._initPlayer(); 
    } 

    componentWillUnmount() { 
    if(this.hls) { 
     this.hls.destroy(); 
    } 
    } 

    playVideo() { 
    let { video : $video } = this.refs; 
    $video.play(); 

    this.setState({isPlaying: true}); 
    } 

    _initPlayer() { 
    if(this.hls) { 
     this.hls.destroy(); 
    } 

    let { url, autoplay, hlsConfig } = this.props; 
    let { video : $video } = this.refs; 
    let hls = new Hls(hlsConfig); 

    hls.attachMedia($video); 

    hls.on(Hls.Events.MEDIA_ATTACHED,() => { 
     hls.loadSource(url); 

     hls.on(Hls.Events.MANIFEST_PARSED,() => { 
     if(autoplay) { 
      $video.play(); 
     } 
     else { 
      $video.pause(); 
     } 
     }); 
    }); 

    this.hls = hls; 
    } 

    render() { 
    let { isMuted, isPlaying, playerId } = this.state; 
    let { controls, width, height } = this.props; 

    return (
     <div key={playerId}> 
     {!isPlaying && 
      <span onClick={this.playVideo}></span> 
     } 
     <video ref="video" 
      id={`react-hls-${playerId}`} 
      controls={controls} 
      width={width} 
      height={height} 
      muted={isMuted} 
      playsinline> 
     </video> 
     </div> 
    ); 
    } 
} 

export default VideoPlayer; 
+0

我們無法猜測您如何實施您的組件來幫助您。請更新更多細節。 –

回答

0

我認爲這個問題是組件的生命週期。

的playVideo - >的setState - > componentUpdate - > componentDidUpdate - 當用戶播放視頻> initPlayer

所以玩家被初始化每次。

您可以覆蓋「shouldComponentUpdate」,以防止更新而不初始化播放器。


+0

你說得對。不應該使用'componentDidUpdate'。我完全刪除它,現在即使改變組件內的狀態,視頻也不會重新初始化。我不需要使用'shouldComponentUpdate'。 – user1087973