React选章节后点击上下集按钮报Cannot read property 'video' of undefined错误
问题根源
你点击左侧章节按钮时,给SelectChapiter传入的是字符串类型的索引(比如'0'/'1'),导致state.indice最终被赋值为字符串。后续点击上/下一章执行加减操作时,会触发字符串拼接逻辑:比如当前indice是字符串'2',执行this.state.indice +1得到的结果是'21',而你的videos数组只有6个元素,索引最大为5,videos[21]自然是undefined,访问它的video属性就触发了你遇到的报错。
另外你代码里还有两个隐性问题:
Previous方法没有绑定this,后续调用时会出现this指向错误- 直接操作DOM修改video元素的src不符合React的最佳实践,建议通过state驱动视图更新
修复方案
- 修改左侧章节按钮的点击参数,把字符串类型的索引改为数字类型
- 在constructor中补全
Previous方法的this绑定 - 优化视频src的赋值逻辑,改用state控制,避免直接操作DOM
修复后完整代码
import React, { Component } from 'react'; import './App.css'; const videos = [ { Chapitre: 'Intro', video: '/Videos/part0 - training 1.mp4' }, { Chapitre: 'The need of 5G', video: '/Videos/Part1.mp4' }, { Chapitre: '5G potential use cases', video: '/Videos/Part 2.mp4' }, { Chapitre: '5G technical requirements', video: '/Videos/Part 3.mp4' }, { Chapitre: 'Timeline for 5G standards and roll out', video: '/Videos/Part 4.mp4' }, { Chapitre: 'Quiz', video: '/Videos/Part 5.mp4' } ]; class App extends Component { constructor(props) { super(props) this.state = { indice: 0 } this.SelectChapiter = this.SelectChapiter.bind(this); this.Next = this.Next.bind(this); this.Previous = this.Previous.bind(this); } SelectChapiter(index) { this.setState({ indice: index }); }; Next () { if(this.state.indice < videos.length -1){ this.SelectChapiter(this.state.indice + 1); } }; Previous () { if(this.state.indice > 0){ this.SelectChapiter(this.state.indice - 1); } } render() { return ( <div> <div className="LeftNav"> <div className="FormationName">5G Associate Training_01M01</div> <div id="Obj">Objective of training</div> <ul className= "chapitres"> <button onClick={() => this.SelectChapiter(0)}>Intro</button><br/> <button onClick={() => this.SelectChapiter(1)}>The need of 5G</button> <button onClick={() => this.SelectChapiter(2)}>5G potential use cases</button> <button onClick={() => this.SelectChapiter(3)}>5G technical requirements</button> <button onClick={() => this.SelectChapiter(4)}>Timeline for 5G standards</button><br/> <button onClick={() => this.SelectChapiter(5)}>Quiz</button> </ul> </div> <div className="control"> <input onClick={this.Previous} className="icon" type="image" src="/Assets/previous.png" alt="上一章" /> <input onClick={this.Next} className="icon" type="image" src="/Assets/next.png" alt="下一章" /> </div> <video className="VidéoSection" controls> <source src={videos[this.state.indice].video} type="video/mp4"/> Your browser does not support the video tag. </video> </div> ); } } export default App;
界面截图

内容的提问来源于stack exchange,提问作者selharem
相关产品推荐
相关产品推荐

