arrays - 仅在 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 天,现在只想要这个解决方案哈哈。在此先感谢您的帮助,我将不胜感激:)
解决方案
推荐阅读
- javascript - Kubernetes 替换部署失败
- python - Drill 无法读取 Spark 生成的 Parquet 中的大部分列
- macos - MacOS Mojave:检查存档器 (ar) 界面时,./configure 脚本失败
- javascript - 缩放图像时是否可以禁用滑动功能?
- laravel - 从 Laravel 的相关模型中获取字段?
- javascript - reactjs通过道具将对象数组从父状态传递给子状态
- elasticsearch - 处理同一搜索字符串上的精确搜索和部分搜索
- python - 为什么(Kivy)下拉菜单不显示?
- c++ - 使用 cmake 将 boost 链接到 c++:命令行编译
- jpa - entityManager.merge(object) 仅保留列表中的最后一条记录