在react项目中显示默认图像

dzhpxtsq  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(270)

我正在使用免费的api检索数据。我正在尝试为没有它们的对象使用默认图像。
这是我的项目结构:

在里面 movies.service.tsx 我获取数据并将从db检索到的值分配给movie对象的属性图片(如果没有值, undefined 分配给以下人员):

import("../images/default-poster.png");

const movieApiBaseUrl = "https://api.themoviedb.org/3";
const posterBaseUrl = "https://image.tmdb.org/t/p/w300";
export interface Movie {
    id: number;
    title: string;
    rating: number;
    description: string;
    picture?: string;
    date: string;
  }

  export function fetchMovies(): Promise<Movie[]> {
   return fetch(
     `${movieApiBaseUrl}/discover/movie?sort_by=year.desc&api_key=${process.env.REACT_APP_API_KEY}`
   )
     .then((res) => res.json())
     .then((res) => mapResult(res.results))
     .catch(() => {
         return [];
     });
 }

 // = movie has to be after const {} here
 function mapResult(res: any[]): Movie[] {
   return res.map((movie) => {
     const {
       id,
       title,
       vote_average,
       overview,
       poster_path,
       date,
     } = movie;
     return {
       id: id,
       title: title,
       rating: vote_average,
       description: overview,
       picture: poster_path ? `${posterBaseUrl}${poster_path}` : undefined,
       date: date,
     };
   });
 }

如何导入文件 default-poster.pngmovies.service.tsx 并将其路径指定给图片属性,而不是指定 undefined 这样我以后就可以用它了 MovieCards.tsx ?
谢谢

mbskvtky

mbskvtky1#

解决方案是将导入“../images/no image available.png”赋值给一个变量,然后将该变量作为三元运算符的第三个操作数传递: picture: poster_path ? ${posterbaseurl}${poster_path} : noImage

相关问题