【问题标题】:Show default image in react project在反应项目中显示默认图像
【发布时间】:2021-09-20 09:47:16
【问题描述】:

我正在使用免费 API 检索数据。我正在尝试为没有它们的对象使用默认图像。

这是我项目的结构:

movies.service.tsx 中,我获取数据并将从数据库检索到的值分配给 movie 对象的属性 picture(如果没有值,@987654324 @ 已分配):

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.png 导入到 movies.service.tsx 并将其路径分配给图片属性,而不是分配 undefined,以便我以后可以在 MovieCards.tsx 中使用它?

谢谢

【问题讨论】:

  • Typescript 不允许我将 img 分配给 picture 属性。我还安慰了 img 值,它等于一个模块
  • 模块默认值:"data:image/png;base64,iVBORw0KGgoAAAA <...>" Symbol(Symbol.toStringTag): "Module" esModule: true __proto: Object

标签: javascript reactjs api fetch default


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-05-07
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 2021-10-23
    相关资源
    最近更新 更多