I am following Next.js tutorial for fetching data
But unlike tutorial, I use axios
. Problem is getInitialProps
does not get the data I want to have.
here is the code:
import axios from "axios";
import Link from "next/link";
const Body = props => (
<div>
<h1>Shows</h1>
<ul>
{props.data.map(({ show }) => (
<li key={show.id}>
<Link as={`/p/${show.id}`} href={`/post?title=${show.title}`}>
<a>{show.name}</a>
</Link>
</li>
))}
</ul>
</div>
);
Body.getInitialProps = async function() {
const res = await axios.get("https://api.tvmaze.com/search/shows?q=batman");
const data = await res.data;
console.log(`Show data fetched. Count: ${data.length}`);
return {
data: data
};
};
export default Body;
To me, the code seems fine but error Unhandled Rejection (TypeError): Cannot read property 'map' of undefined
keeps occurring.
I have solved the issue.
It occurred because I broke a simple rule.
According to next.js document , there is a note saying
Note: getInitialProps
can not be used in children components. Only in pages
.
So when I fetcehd that data at index.js
, it successfully get the data I want to have.
Thought I could use getInitialProps
in any components just like componentDidMount
.
That was a problem.
我可能是错的,如果我错了,请告诉我,我会删除我的答案,但我认为这是因为您没有该道具的默认值,并且不会立即调用获取数据的方法,因此有一个您的道具undefined
并且您在未定义的道具上调用map
那一刻。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.