【发布时间】: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