我正在尝试开发已被更改的React Component。因此,我设置了isSelected
来检查是否选中了该项目,如下所示:
src / components / common / Youtube.js
const Youtube = ({ video, handleSelect, selectedVideos }) => {
const url = "https://www.youtube.com/embed/" + video.id.videoId;
const videoInfo = video.snippet;
const isSelected = selectedVideos.find(v => v.uid === video.id.videoId);
return (
<div>
{isSelected ? (
<Button onClick={() => handleSelect(video.id.videoId)>
<p>Select</p>
</Button>
) : (
<p>Selected</p>
)}
</div>
);
};
但是isSlected
无法正常工作。选择该项目而不加载时,该应用程序应该可以无缝运行。
src / components / common / YoutubeList.js
const YoutubeList = ({ videos, handleSelect, selectedVideos }) =>
videos.map(video => (
<Youtube
video={video}
handleSelect={handleSelect}
selectedVideos={selectedVideos}
/>
));
export default YoutubeList;
src / components / Home.js
const YOUTUBE_API_KEY = process.env.REACT_APP_YOUTUBE_API_KEY;
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
videos: [],
selectedVideos: []
};
}
onSerchYoutube = keyword => {
const url = `https://www.googleapis.com/youtube/v3/search?type=video&part=snippet&q=${keyword}&maxResults=3&key=${YOUTUBE_API_KEY}`;
axios
.get(url)
.then(response => {
this.setState({
videos: response.data.items
});
})
.catch(() => {
console.log("Failed to fetch videos :(");
});
};
_handleSelect = id => {
const { selectedVideos } = this.state;
selectedVideos.push({ uid: id });
console.log("selected!" + id);
console.log("selected", selectedVideos);
};
render() {
return (
<div>
<div>
<Header title={"Home"} />
<SearchForm onSerchYoutube={this.onSerchYoutube} />
<YoutubeList
videos={this.state.videos}
handleSelect={this._handleSelect}
selectedVideos={this.state.selectedVideos}
/>
</div>
</div>
);
}
}
export default Home;