【发布时间】:2021-04-05 19:13:20
【问题描述】:
通常,如果我在使用 .map 时遇到错误,那是因为我使用该方法的数组不存在或根本不是数组。
有时我从 fetch 返回一个 JSON 对象,并尝试在对象上使用 .map 而不是对象内部的数组。
这些都是菜鸟错误,我是菜鸟。但是,在以下情况下,我确定我在 JSON 对象内部的数组上调用 .map。
怎么做?
- 因为以下代码在本地开发中工作和
- 因为我使用 console.log(albums) 来确保我正在迭代一个数组。
当我在 Vercel 上部署这个 next.js 应用程序时,我收到以下错误:
> Build error occurred
21:23:30 TypeError: albums.map is not a function
21:23:30 at getStaticPaths (/vercel/workpath0/.next/serverless/pages/albums/[id].js:306:16)
21:23:30 at processTicksAndRejections (internal/process/task_queues.js:97:5)
21:23:30 at async buildStaticPaths (/vercel/workpath0/node_modules/next/dist/build/utils.js:16:80)
21:23:30 at async Object.isPageStatic (/vercel/workpath0/node_modules/next/dist/build/utils.js:23:549) {
21:23:30 type: 'TypeError'
21:23:30 }
21:23:30 error Command failed with exit code 1.
21:23:30 info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
21:23:30 Error: Command "yarn run build" exited with 1
21:23:32 Done with "package.json"
这是此错误所指的页面:
import React from "react";
import { useQuery, useMutation, useQueryClient } from "react-query";
import Image from "next/image";
import { queryAlbum } from "../../api/albums/[id]";
import { queryAlbums } from "../../api/albums";
import Form from "../../../components/styles/Form";
import Button from "../../../components/styles/Button";
import Container from "../../../components/styles/AlbumsShow";
async function createPicture(pictureData) {
const response = await fetch(`/api/pictures/create`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(pictureData),
});
const { picture } = response.json();
return picture;
}
async function deletePicture(pictureId) {
await fetch(`/api/pictures/delete`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(pictureId),
});
}
export async function getStaticPaths() {
const albums = queryAlbums();
const paths = [];
await albums.map((album) => {
return paths.push({
params: {
id: album.id.toString(),
},
});
});
return {
paths,
fallback: false,
};
}
export async function getStaticProps({ params }) {
const response = await queryAlbum(params.id);
const data = await JSON.stringify(response);
const initialAlbumData = await JSON.parse(data);
return {
props: {
initialAlbumData,
},
};
}
export default function Album({ initialAlbumData }) {
...all the code for the component
);
}
这里是查询函数:
import { PrismaClient } from "@prisma/client";
export async function queryAlbum(albumId) {
const prisma = new PrismaClient({ log: ["query"] });
try {
const album = await prisma.album.findUnique({
where: {
id: parseInt(albumId),
},
include: {
pictures: true,
},
});
return album;
} catch (error) {
return { error: error };
} finally {
prisma.$disconnect();
}
}
export default async function answerQuery(req, res) {
// get [id] from url
const {
query: { id },
} = req;
const album = await queryAlbum(id);
res.json({ album: album });
}
和:
import { PrismaClient } from "@prisma/client";
export async function queryAlbums() {
const prisma = new PrismaClient({ log: ["query"] });
try {
const albums = await prisma.album.findMany();
return albums;
} catch (error) {
return { error: error };
} finally {
prisma.$disconnect();
}
}
export default async function Albums(req, res) {
const albums = await queryAlbums();
res.json({ albums: albums });
}
关于我选择导入 queryAlbum 和 queryAlbums 的原因,这里有一个 Git 上的线程,我曾经将我的代码基于: https://github.com/vercel/next.js/discussions/13648
【问题讨论】:
-
我觉得
/api/下的api应该是作为服务调用的,你是作为方法调用的 -
你
const albums = await queryAlbums();可能没有得到正确的数据,请检查该行的响应是什么 -
@Swaraj Gandhi 谢谢你的建议。当我 console.log(albums) 时,它返回一个专辑数组。
-
它可能什么都不是,但是 await 通常不应该用在非异步函数上。
.map是同步的 -
@Yaakov Ainspan 我同意。事实上,我只是在用尽其他选项后才添加“等待”,然后我才开始不顾一切地尝试。上面的代码也可以在 .map 前面没有“等待”的情况下工作。