首页 > 解决方案 > 将图像从 React 项目导入组件

问题描述

我正在使用 React 和 Typescript 构建一个应用程序。

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

这是我的项目的结构:

项目结构

movies.service.tsx我获取数据并将从数据库中检索到的值分配给电影对象的属性图片(如果没有值,我想为其分配路径):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 分配给图片属性。我还安慰了 img 值,它等于一个模块:

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

我需要将图像的路径分配给picture属性,以便以后可以在MovieCards.tsx组件中使用它们。

我应该改变什么?

谢谢!

标签: javascriptreactjstypescriptapiasynchronous

解决方案


解决方案是将默认图像导入到movies.service.tsx

import noImage from '../images/no-image-available.png';

然后将变量noImage作为三元运算符的第三个操作数传递: picture: poster_path ? `${posterBaseUrl}${poster_path}` : noImage,


推荐阅读