React嵌入YouTube播放器时为何playerState状态无法渲染更新
问题根源
你的状态不更新核心是对react-player的事件回调传参逻辑理解错误,另外还有两处会导致异常的笔误:
- 错误调用API获取状态:
react-player已经对原生YouTube iframe API做了封装,onPlayerStateChange触发时,第一个参数直接就是当前播放状态对应的数字编码,不是原生API的event对象。你写的e.target.getPlayerState()根本访问不到播放器实例,拿不到返回值,状态自然永远停留在初始值。额外包的async/await+Promise.all完全是多余逻辑。 - 传入无效组件属性:你给
ReactPlayer传入的playerState={this.state.playerState}不属于组件支持的合法属性,传了也不会产生任何作用。 - 组件导出名称错误:你定义的组件类名是
VideoPlayer,最后导出却写YouTubePlayer,会直接导致组件引用时报错。
修复后代码
直接替换成下面的代码即可正常获取播放状态:
import React from 'react'; import ReactPlayer from "react-player" class VideoPlayer extends React.Component { constructor(props) { super(props); this.state = { playerState: "Unstarted", youtubeIsClicked: false, }; } // 回调直接返回状态码,不需要传事件对象、不需要异步调用API handleVideoPlayerState = (stateCode) => { switch (stateCode) { case -1: console.log('onPlayerStateChange', stateCode); this.setState({ playerState: "Unstarted" }) break; case 0: console.log('onPlayerStateChange', stateCode); this.setState({ playerState: "Ended" }) break; case 1: console.log('onPlayerStateChange', stateCode); this.setState({ playerState: "Playing" }) break; case 2: console.log('onPlayerStateChange', stateCode); this.setState({ playerState: "Paused" }) break; case 3: console.log('onPlayerStateChange', stateCode); this.setState({ playerState: "Buffering" }) break; case 5: console.log('onPlayerStateChange', stateCode); this.setState({ playerState: "Video cued" }) break; default: break } } handleYouTubeClick = () => { this.setState({ youtubeIsClicked: true, }); } render() { return ( <div style={{ width: "80%", margin: "0 auto" }}> <h1>Video Player</h1> <button onClick={this.handleYouTubeClick}>Youtube</button> {this.state.youtubeIsClicked && ( <div> <ReactPlayer url="https://youtu.be/2XsP4I9ds4c" onPlayerStateChange={this.handleVideoPlayerState} /> <p>Playback State: {this.state.playerState}</p> </div> )} </div> ); } } // 修正导出组件名和定义的类名一致 export default VideoPlayer
修改说明
- 移除了多余的异步调用逻辑,直接使用回调返回的状态码做映射判断
- 删除了ReactPlayer上不被识别的无效
playerState传参 - 修正了组件导出的名称笔误
- 保留了你原本写的状态码和展示文本的映射逻辑,这部分不需要改动
内容的提问来源于stack exchange,提问作者lia
相关产品推荐
相关产品推荐

