我正在Next js工作,我正试图通过api获取记录,但现在我得到以下错误
"Cannot read property 'map' of undefined"
这是我的代码(components/Blog.jsx)
export default function Blog({ people }) {
return (
<div>
{people.map(person => (
<>
<h1>{person.name}</h1>
<h2>Website: {person.website}</h2>
Email: <code>{person.email}</code>
</>
))}
</div>
);
};
export const getStaticProps = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const people = await response.json();
return {
props: {
people
}
};
};
一种可能的修复方法是在返回Blog()函数之前执行如下操作
people = people || []
这将使人们有一个默认值,这样当你试图映射它时,它就不能被定义了
也许你还没有从API中获取数据。如果未获取数据,则预定义数据为空数组。试试这个
export default function Blog({ people = [] }) {
.....
我希望这能成功。
看了你的问题后,我明白了,它的发生要么是因为人的未定义值
export default function Blog({ people }) {
return (
<div>
{people.map(person => (
<>
<h1>{person.name}</h1>
<h2>Website: {person.website}</h2>
Email: <code>{person.email}</code>
</>
))}
</div>
);
};
export const getStaticProps = async () => {
try{
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const people = await response.json();
return { props: { people} }
}catch{
return { props: { } }
}
};
根据文档说明,我们不能在组件级使用getStaticProps
函数。我们应该只在一个页面中使用它。请阅读本节以更好地理解https://nextjs.org/docs/basic-features/data-fetching/get-static-props#where-can-i-use-getstaticprops。还要确保将people初始化为空数组->人=[]。希望这个逻辑能解决你的问题