Обновление видеоэлемента src с разными потоками через URL-адрес большого двоичного объекта

Мой компонент реакции «VideoPlayer» не обновляет свой атрибут src при изменении его реквизита.

Каждый раз, когда вызывается getUrlStreamForMostRecentMP4OnDb(), создается новый объект URL большого двоичного объекта. Этот объект передает самое последнее видео, добавленное в базу данных. Независимо от того, какое последнее видео в базе данных, элемент видео всегда отображает одно и то же исходное видео.

App.js

import React, { Component } from "react";
import VideoPlayer from "./VideoPlayer";


export default class App extends Component {
  constructor(props, context) {
    super(props, context);

    this.getUrlStreamForMostRecentMP4OnDb = this.getUrlStreamForMostRecentMP4OnDb.bind(
      this
    );

    this.state = {
      playerSource: null,
    };
  }


  async getUrlStreamForMostRecentMP4OnDb() {
    fetch("http://localhost:4000/ytdl/streamMP4")
      .then(re => re.blob())
      .then(blob => URL.createObjectURL(blob))
      .then(url => {
        this.setState({ playerSource: url });
      })
      .catch(err => {
        console.log(err);
      });
  }

  render() {
    return (
      <div>
        <button onClick={this.getUrlStreamForMostRecentMP4OnDb}>
          Get url stream for most recent mp4 from db.
        </button>
        {this.state.playerSource ? (
          <VideoPlayer
            key={this.state.playerSource}
            playerSource={this.state.playerSource}
          />
        ) : (
          <div />
        )}
      </div>
    );
  }
}

VideoPlayer.js

import React, { Component } from "react";

export default class VideoPlayer extends Component {
  constructor(props, context) {
    super(props, context);
  }

  render() {
    return (
      <div>
        <video
          id="video"
          width={300}
          ref="player"
          muted={true}
          autoPlay={true}
          loop
          crossOrigin="anonymous"
          src={this.props.playerSource}
        >
        </video>
      </div>
    );
  }
}

person Oliver    schedule 07.05.2019    source источник
comment
Вы уверены, что ваше состояние обновляется в вашем родительском компоненте с новым URL-адресом?   -  person James Ives    schedule 08.05.2019
comment
Да. Я только что записал в консоль this.state.playerSource после двукратного получения данных и получил следующее: › blob:localhost:3000/6c6fedfb-5e51-41a3-8e71-101724ecd3b8 › blob:localhost:3000/77e994d4-a69f-4995-b556-d8c9dc5cf7d8   -  person Oliver    schedule 08.05.2019
comment
Что произойдет, если вы добавите key={this.props.playerSource} к элементу <video>?   -  person James Ives    schedule 08.05.2019
comment
Добавление ключа к элементу <video> дает тот же результат.   -  person Oliver    schedule 08.05.2019


Ответы (1)


Я знаю, что это старый вопрос, но я заставил его работать, манипулируя домом напрямую следующим образом:

const onUpload = ({ event, ContentId, ContentIndex }) => {
    if (event.target.files.length) {
        var UploadedVideo = event.target.files[0];

        var MediaUrl = URL.createObjectURL(UploadedVideo);

        var VideoElement = document.getElementById(`video_${ContentId}`);
        if (VideoElement) {
            VideoElement.src = MediaUrl;
            VideoElement.load();
        }
    }
}
person Ridge Robinson    schedule 25.02.2021