我很难理解React是如何运作的。我正在制作一个youtube预览器,但我无法弄清楚如何在每次传递新的searchQuery时使Display组件显示列表中的第一个结果。这是我的代码(我知道我已经复制了很多代码,但现在只剩下一个代码了):
class App extends Component {
constructor(props){
super(props);
this.state = {
searchQuery: 'technology',
results: [],
currentVideo: ''
};
this.searchVideos = this.searchVideos.bind(this);
this.getData = this.getData.bind(this);
this.handleClick = this.handleClick.bind(this);
}
getData() {
axios
.get(`https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=20&order=rating&q=${this.state.searchQuery}&key=${APIkey}`)
.then(res => {
let results = res.data.items.map(item => {
return item;
})
this.setState({results: results, currentVideo: results[0].id.videoId});
});
}
componentWillMount() {
this.getData();
}
componentDidUpdate() {
axios
.get(`https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=20&order=rating&q=${this.state.searchQuery}&key=${APIkey}`)
.then(res => {
let results = res.data.items.map(item => {
return item;
})
this.setState({results});
});
}
searchVideos() {
let searchQuery = this.refs.searchQuery.refs.searchQuery.value;
this.setState({searchQuery});
}
handleClick(video) {
this.setState({currentVideo: video.id.videoId});
}
render() {
return (
<div className="container">
<div className="row">
<Search onChange={this.onChangeEvent} searchVideos={this.searchVideos} ref="searchQuery" />
</div>
<div className="row">
<Display currentVideo={this.state.currentVideo} />
<VideoList handleClick={this.handleClick} videos={this.state.results} />
</div>
</div>
);
}
}