【问题标题】:How to handle React life cycle with http live streaming HLS?如何使用 http 直播 HLS 处理 React 生命周期?
【发布时间】:2017-09-07 14:17:11
【问题描述】:

我正在使用这个 hls.js player 和 React 来流式传输 m3u8。我有一个组件 VideoPlayer 来设置 hls.js 播放器。这个组件有几个状态属性,比如isPlayingisMuted。我有自定义按钮,onClick 将组件函数调用到setState,但这当然会重新渲染组件,并且我猜视频流会重新挂载并恢复到原始状态,即恢复到第一帧和停了下来。一般来说,您如何处理流视频的应用程序(redux)或本地状态更改?我注意到,每当 redux 商店更新或本地状态发生变化时,视频总是会出现这种“闪烁”(即重新渲染)。

更新代码示例:

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;

【问题讨论】:

  • 我们无法猜测您如何实现组件来帮助您。请更新更多细节。

标签: reactjs redux rendering http-live-streaming hls.js


【解决方案1】:

我认为问题在于组件的生命周期。

playVideo -> setState -> componentUpdate -> componentDidUpdate -> initPlayer

所以每次用户播放视频时都会初始化播放器。

您可以覆盖“shouldComponentUpdate”,以便在不初始化播放器的情况下阻止更新。


【讨论】:

  • 你是对的。 componentDidUpdate 甚至不应该被使用。我完全删除了它,现在即使我更改组件内的状态,视频也不会重新初始化。我不需要使用shouldComponentUpdate
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多