【问题标题】:.map is not a function Vercel Deploy.map 不是 Vercel 部署的函数
【发布时间】:2021-04-05 19:13:20
【问题描述】:

通常,如果我在使用 .map 时遇到错误,那是因为我使用该方法的数组不存在或根本不是数组。

有时我从 fetch 返回一个 JSON 对象,并尝试在对象上使用 .map 而不是对象内部的数组。

这些都是菜鸟错误,我是菜鸟。但是,在以下情况下,我确定我在 JSON 对象内部的数组上调用 .map。

怎么做?

  1. 因为以下代码在本地开发中工作和
  2. 因为我使用 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 前面没有“等待”的情况下工作。

标签: next.js prisma vercel


【解决方案1】:

我分两步解决了这个问题。

首先,我在 Git 上找到了答案:https://github.com/vercel/next.js/issues/8041。基本上,我需要做的就是删除“babel”配置。我真的不知道为什么这个答案有效。我会调查一下并在这里发布更新。

导致部署错误的package.json:

{
  "name": "photo_album",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "prisma": "prisma",
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "@prisma/client": "^2.13.1",
    "babel-plugin-styled-components": "^1.12.0",
    "next": "10.0.3",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "react-query": "^3.5.1",
    "styled-components": "^5.2.1"
  },
  "devDependencies": {
    "@prisma/cli": "^2.13.1"
  },
  "babel": {
    "presets": [
      "@babel/preset-react"
    ],
    "env": {
      "development": {
        "presets": [
          "next/babel",
          "@babel/preset-react"
          "next/babel"
        ],
        "plugins": [
          [

答案:

{
  "name": "photo_album",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "prisma": "prisma",
    "dev": "next dev",
    "build": "next build",
    "start": "next start -p $PORT",
    "postinstall": "prisma generate",
    "heroku-postbuild": "npm run build"
  },
  "dependencies": {
    "@prisma/client": "^2.13.1",
    "babel-plugin-styled-components": "^1.12.0",
    "next": "10.0.3",
    "react": "16.13.0",
    "react-dom": "17.0.1",
    "react-query": "^3.5.1",
    "styled-components": "^5.2.1",
    "@prisma/cli": "^2.13.1",
    "@babel/core": "^7.12.10",
    "@babel/preset-react": "^7.12.10"
  },
  "devDependencies": {
    "@babel/core": "^7.12.10",
    "@babel/preset-react": "^7.12.10",
    "@prisma/cli": "^2.13.1"
  }
}

第二步涉及将 getStaticProps 更改为 getServerSideProps 并删除 getStaticPaths。 下面是 getServerSideProps 的样子:

export async function getServerSideProps(context) {
  const response = await queryAlbum(context.query.id);
  const data = await JSON.stringify(response);
  const initialAlbumData = await JSON.parse(data);

  if (!initialAlbumData) {
    return {
      notFound: true,
    };
  }

  return {
    props: {
      initialAlbumData,
    },
  };
}

【讨论】:

    【解决方案2】:

    查看导入,似乎这些是您创建的 api。这些不是普通方法,它们是http方法,可以通过http(http调用)消费。

    import { queryAlbum } from "../../api/albums/[id]";
    import { queryAlbums } from "../../api/albums";
    

    我正在使用fetch 来使用各自的api。

    export async function getStaticPaths() {
      const data = await fetch('/api/albums');
      const albums = await data.json();
      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 fetch(`/api/albums/${params.id}`);
      const data = await response.json();
      return {
        props: {
          initialAlbumData: data,
        },
      };
    }
    

    【讨论】:

    • 我真的很喜欢这个建议。但是,next.js 不接受 getStatisPaths() 中的相对路径
    • 你试过了吗?我可以看到你使用了其他 api /api/pictures/create,它有效吗?
    • 是的。不幸的是,next.js 不接受 getStaticPaths 或 getStaticProps 中的相对路径。它将允许我编写的其他函数中的相对路径
    • 你是对的..你能分享queryAlbums和queryAlbum的代码吗?
    • 当然!我刚刚发布了它们
    猜你喜欢
    • 1970-01-01
    • 2020-11-06
    • 2020-08-26
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2023-02-12
    • 2021-05-31
    • 2021-12-06
    相关资源
    最近更新 更多