首页 > 解决方案 > React 'isSelected' 不适用于检查它是否被选中

问题描述

我正在使用 React 应用程序,用户在从 Youtube 获取的随机视频上选择视频。我希望它能够识别那些被选中的或未被选中的。但isSelected不工作。

const isSelected = selectedVideos.find(v => v.uid === video.id.videoId);

实际上,它没有定义。我不应该用filter这个吗?

我的代码:

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 ? (
        <Card>
          <iframe
            id="ytplayer"
            type="ytplayer"
            width="100%"
            height="270"
            src={url}
            frameborder="0"
          />
          <CardActionArea
            onClick={() => handleSelect(video.id.videoId)}
          >
            <h2>{videoInfo.title}</h2>
            <p>{videoInfo.description}</p>
          </CardActionArea>
        </Card>
      ) : (
        <p>Selected</p>
      )}
    </div>
  );
};

export default Youtube;
const YoutubeList = ({ videos, handleSelect, selectedVideos }) =>
  videos.map(video => (
    <Youtube
      video={video}
      handleSelect={handleSelect}
      selectedVideos={selectedVideos}
    />
  ));

export default YoutubeList;
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={"Create"} />
          <SearchForm onSerchYoutube={this.onSerchYoutube} />
          <YoutubeList
            videos={this.state.videos}
            handleSelect={this._handleSelect}
            selectedVideos={this.state.selectedVideos}
          />
        </div>
      </div>
    );
  }
}

export default Home;

额外的

样本 - selectedVideo

0: {uid: "kY6bGqtYD3k"}
1: {uid: "kY6bGqtYD3k"}
length: 2
__proto__: Array(0)

样本 - 视频

etag: ""j6xRRd8dTPVVptg711_CSPADRfg/0lHCSlZJYu6Fcoet132S1tSh4G0""
id:
kind: "youtube#video"
videoId: "hBv1SHjqd1Q"
__proto__: Object
kind: "youtube#searchResult"
snippet:
channelId: "UCfCKvREB11-fxyotS1ONgww"
channelTitle: "Mark Felton Productions"
description: "Did the Germans really create a stay-behind guerrilla force known as 'Werewolf' to continue the fight behind Allied lines in 1945? Yes, they did, but here you will ..."
liveBroadcastContent: "none"
publishedAt: "2019-03-27T16:55:23.000Z"
thumbnails: {default: {…}, medium: {…}, high: {…}}
title: "SS Werewolves - The True Story"

标签: javascriptreactjs

解决方案


使用some而不是find.

find将返回匹配对象的整个值,如果有或没有,您只需要布尔信息。为此,您可以使用some,如果存在或不存在,它将仅返回布尔信息。

只是为了好奇,some类似于includes,但some接收一个函数作为谓词,同时includes接收一个文字值。


推荐阅读