如何解决使用getInitialProps会产生TypeError:无法读取未定义的属性“ map”
我已经看到很多与getInitialProps
和getStaticProps
有关的问题,但我自己还无法解决。
我只是试图加载一些json数据(我进行了console.logging,并知道它不是未定义的),然后将其传递给我的Main
组件:
import Card from "./components/Card";
import data from "../data/data.json";
const Main = ({ cards }) => {
return (
<div}>
{cards.map((card) => {
<Card key={card.id} card={card} />;
})}
</div>
);
};
Main.getInitialProps = async (context) => {
return {
props: { cards: data },};
};
export default Main;
TypeError:无法读取未定义的属性“ map”
我也尝试过getStaticProps
,同样的问题。
我在做什么错了?
解决方法
根据the docs,此方法应该有效:
import Card from "./components/Card";
import data from "../data/data.json";
const Main = ({ cards }) => {
return (
<div}>
{cards.map((card) => {
<Card key={card.id} card={card} />;
})}
</div>
);
};
Main.getInitialProps = async (context) => {
// await for `data`
return {
cards: data,};
// ^-- note the change,you nested your object inside a `props` property
};
export default Main;
,
Page.getInitialProps = async (ctx) => {
const res = await fetch('https://api.url.com')
const json = await res.json()
return { stars: json.stargazers_count }
}
您必须更改此
return {
props: { cards: data },};
应使用此:
return { cards: data }
更多信息,您可以查看:docs
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。