【发布时间】:2019-09-25 15:32:43
【问题描述】:
我的反应组件 'VideoPlayer' 不会在其 props 更改时更新其 src 属性。
每次调用 getUrlStreamForMostRecentMP4OnDb() 都会创建一个新的 blob 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>
);
}
}
【问题讨论】:
-
您确定您的状态正在使用新的 url 在您的父组件中更新吗?
-
是的。我只是在两次获取数据后控制台记录了 this.state.playerSource 并收到以下信息:> blob:localhost:3000/6c6fedfb-5e51-41a3-8e71-101724ecd3b8 > blob:localhost:3000/77e994d4-a69f-4995-b556-d8c9dc5cf7d8
-
如果将
key={this.props.playerSource}添加到<video>元素会发生什么? -
在
<video>元素中添加一个键具有相同的结果。
标签: reactjs stream video-streaming blob src