出现“无法读取未定义的属性(读取'map')”错误。即使数组已声明并导入 [closed]

Getting "Cannot read properties of undefined (reading 'map')" Error. Even though the array is declared and imported [closed]

提问人:Francis Sales 提问时间:11/8/2023 最后编辑:derloopkatFrancis Sales 更新时间:11/12/2023 访问量:86

问:


这个问题是由错别字或无法再现的问题引起的。虽然类似的问题可能在这里是主题,但这个问题的解决方式不太可能帮助未来的读者。

10天前关闭。

我正在尝试映射数组并显示名称,以便最终可以动态路由到每个人的页面。尽管已声明数组,但该数组仍返回为未定义。所以这就是.map不起作用的原因。但是我哪里出了问题呢?

我有这个数组的代码 /lib/api

export async function getCastDetails() {
    const members = (
      {
        id: "1",
        name: "name one"
      },
      {
        id: "2",
        name: "name two"
      },
      {
        id: "3",
        name: "name three"
      }
    )
    return members;
  }

我有这段代码来映射数组并在页面上显示名称

import { getCastDetails } from "@/lib/api";

export async function getStaticProps() {
    const castData = await getCastDetails();
    return {
        props: {
            castData,
        }
    }
}
const CastCarousel = ({ castData }) => {

    console.log(castData);
    return (
        <div>
            {castData.map(member => (
                <div
                    key={member.id}
                >
                    <a>{member.name}</a>
                </div>
            ))}
        </div>
    )
}

export default CastCarousel

然后我显示在我的索引页上

编辑: 我相信我需要通过索引页上的组件传递 castData,但我无法弄清楚如何做到这一点。

这是我的索引页面的样子

import CastCarousel from "@/components/CastCarousel"

const Cast = () => {
    return (
        <main>
            <div className="flex flex-col justify-center items-center h-screen">
                <div>
                    <h1
                        className="text-6xl relative"
                    >Explore The Guys</h1>
                </div>
                <div className="">
                    <CastCarousel/>
                </div>
            </div>
        </main>
    )
}

export default Cast
JavaScript Reactjs 数组 next.js

评论


答:

1赞 Elvis Adomnica 11/8/2023 #1

数组使用 而不是 .我,你的情况,这个函数应该是:[]()

export async function getCastDetails() {
    const members = [
      {
        id: "1",
        name: "name one"
      },
      {
        id: "2",
        name: "name two"
      },
      {
        id: "3",
        name: "name three"
      }
    ]
    return members;
}

否则,发生的情况是分配了该枚举中的最后一个对象(ID 为 3 的对象),这就是您收到错误的原因,因为它是一个对象而不是数组。members.map

评论

0赞 Elvis Adomnica 11/8/2023
我还没有看其余的代码,所以你可能需要一些额外的修复,但这个是从开始的
0赞 Phil 11/8/2023
发现得很好,但这并不能解释错误消息。如果是最后一个对象,则错误为“map is not a function”castData
0赞 Elvis Adomnica 11/8/2023
我同意,我只是在阅读代码时停下来。我没有精力继续,对不起
0赞 Francis Sales 11/8/2023
非常感谢您的回复。我确实注意到了括号错误并修复了它。但错误仍然存在。数组仍返回为未定义。知道为什么吗?
0赞 Elvis Adomnica 11/8/2023
@FrancisSales哥本哈根已经快到午夜12:30了,所以我不得不收工了。早上会退房,如果没有人帮你,我会尽力这样做。