我有以下两个班级。我认为这里的主要问题是render函数传递初始状态而不是在YTsearch API的帮助下更新的更新状态。如果我在控制台上打印有关视频的信息,我会根据对象收到有关搜索查询的相关信息。但是当将这些对象传递给新的Component(Title)时,它似乎是未定义的(null)。
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Component } from 'react';
import Youtube from './Youtube';
import Title from './Title';
import YTSearch from 'youtube-api-search';
const key = '************************************';
class YoutubeVideo extends React.Component {
constructor(props) {
super(props);
this.state = {video:'', selectedVideo:'', received: false};
this.getvideos();
}
getvideos() {
YTSearch({key: key, term: 'football'}, (videos) => {
this.setState({
videos: videos,
selectedVideo: videos[0],
received : true
});
});
}
render() {
if (this.state.received){
return (
<Title videoTitle={ this.state.selectedVideo }/>
)
}
return (
<div>
</div>
)
}
}
ReactDOM.render(
<YoutubeVideo />,
document.getElementById('root')
);
Title.js
import React, { Component } from 'react';
class Title extends Component {
render () {
const video = this.props.videoTitle;
return (
<div>
<div>{ this.video.snippet }</div>
<div>{ this.video.snippet }</div>
</div>
)
}
}
export default Title;
我在Title.js中收到以下错误:
TypeError: Cannot read property 'snippet' of undefined
请帮忙。
答案 0 :(得分:0)