从react项目将图像导入组件

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

我正在用react和typescript构建一个应用程序。
我正在使用免费的api检索数据。我正在尝试为没有它们的对象使用默认图像。
这是我的项目结构:

在里面 movies.service.tsx 我获取数据并将从db中检索到的值分配给movie对象的属性picture(如果没有值,我想将其分配为 default-poster.png ):

import * as img from '../images/default-poster.png';

console.log('img ', img);

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}` : img,
       date: date,
     };
   });
 }

然而,我不允许通过typescript将img分配给picture属性。我还安慰了img值,它相当于一个模块:

Module default: "data:image/png;base64,iVBORw0KGgoAAAA <...>" Symbol(Symbol.toStringTag): "Module" esModule: true __proto: Object

我需要将图像的路径分配给 picture 属性,以便我可以在 MovieCards.tsx 组件以后。
我应该换什么?
谢谢

hgtggwj0

hgtggwj01#

解决方案是将默认图像导入到 movies.service.tsx : import noImage from '../images/no-image-available.png'; 然后传递变量 noImage 作为三元运算符的第三个操作数: picture: poster_path ?${posterBaseUrl}${poster_path}: noImage,

相关问题