首页 > 解决方案 > 仅在 ReactJs 中添加到数组或渲染不具有等于 null 的特定属性的项目

问题描述

我正在尝试使用电影预告片制作 netflix 的克隆,并使用以下代码实现:

import React, { useEffect, useRef, useState } from "react";
import "./Row.css";
import axios from "./axios";
import ArrowForwardIosIcon from "@material-ui/icons/ArrowForwardIos";
import YouTube from "react-youtube";
import movieTrailer from "movie-trailer";
import { ContactlessOutlined, MovieSharp } from "@material-ui/icons";
function Row({ title, fetchUrl, isLargeRow = false }) {
  const [movies, setMovies] = useState([]);
  const [trailerUrl, setTrailerUrl] = useState("");
  const [trailerList, setTrailerList] = useState("");

  const base_url = "https://image.tmdb.org/t/p/original/";

  const posterRowRef = useRef();

  const handleClick = (movie) => {
    console.log(movie.videoUrl);

    if (trailerUrl) {
      setTrailerUrl("");
    } else {
      console.log(movie);
      movieTrailer(null, {
        tmdbId: movie.id,
        apiKey: "***************************",
      }).then((url) => {
        console.log("URL", url);
      });
    }
  };


  useEffect(() => {
    async function fetchData() {
      let request = await axios.get(fetchUrl);

      request.data.results.forEach((movie, index) => {
        movieTrailer(null, {
          tmdbId: movie.id,
          apiKey: "***************************",
        }).then((response) => {
          if (response == null) {
            movie["videoUrl"] = null;
          } else {
            movie["videoUrl"] = response;
            setMovies(movie);
          }
        });
      });
      // setMovies(request.data.results);

      return request;
    }
    fetchData();
  }, [trailerUrl]);

  return (
    <div className="row">
      <h2>{title}</h2>{" "}
      <div ref={posterRowRef} className="row__posters">
        {movies.map((movie, index) => {
          // console.log(trailerList[index]?.videoUrl);
          return (
            <img
              key={movie.id}
              onClick={() => handleClick(movie)}
              className={`row__poster ${isLargeRow && "row__posterLarge"}`}
              src={`${base_url}${isLargeRow ? movie.poster_path : movie.backdrop_path}`}
              alt=""
            />
          );
        })}
      </div>
    </div>
  );
}

export default Row;

出于显而易见的原因阻止了我的 API 密钥。

我正在尝试从 Tmdb 数据库中提取视频列表,然后通过 movie-trailer 节点包运行它的 id。它使用 tmdb 电影 ID 在 youtube 上搜索其预告片,如果有预告片,它将返回链接。

如果 videoUrl 存在,它实际上会正确添加,如果不存在,则将其设置为 null。

但是,被渲染的电影数组要么仍然有电影,当我在控制台中单击它时,它会显示 videoUrl:null,但它仍然呈现在屏幕上,或者如果我尝试在链接的索引处拼接数组它是空的,它不会工作。

我相信我快到了我只是不知道如何仅将带有 url 的视频推送到数组,或者当我尝试在返回 jsx 中使用三元运算符进行条件渲染时,什么都不会渲染。我真的很困惑为什么我不能让它工作,我老实说放弃了。

我一直在努力自学编程和自学,但我已经为此工作了 2 天,现在只想要这个解决方案哈哈。在此先感谢您的帮助,我将不胜感激:)

标签: arraysreactjsreact-hooksarray.prototype.map

解决方案


推荐阅读