Next.js使用getServerSideProps时遇TypeError: posts.map is not a function
Next.js 服务端渲染拆分代码后map调用报错问题
我在学习Next.js服务端渲染教程时,发现将fetch逻辑写在同一个index.js文件中可以正常运行,但拆分到单独工具文件后,调用posts.map时出现TypeError: posts.map is not a function错误。
正常运行的代码(/pages/posts/index.js)
export default function index({ posts }) { return ( <div> <h2>Posts API</h2> <ul> {posts.map((post) => { return <li key={post.id}>{post.title}</li>; })} </ul> </div> ); } export async function getServerSideProps() { const res = await fetch(`https://jsonplaceholder.typicode.com/posts`); const posts = await res.json(); console.log(posts); return { props: { posts } }; }
拆分后报错的代码
/pages/posts/index.js
import { userGetPosts } from '../lib/posts'; export async function getServerSideProps(){ const posts = await userGetPosts(); //const data = JSON.parse(JSON.stringify( posts)) console.log(posts); return { props: { posts } }; } export default function Home({ posts }) { return ( <Layout home> <Head> <title>{siteTitle}</title> </Head> <section className={`${utilStyles.headingMd} ${utilStyles.padding1px}`}> <h2 className={utilStyles.headingLg}>Blog</h2> <ul> {/* 启用这段代码会抛出错误 */} {/* {posts.map((post) => { return <li key={post.id}>{post.title}</li>; })} */} </ul> </section> </Layout> ); }
../lib/posts.js
export async function userGetPosts (){ const res = await fetch(`https://jsonplaceholder.typicode.com/posts`); {/* 必须转成文本,否则index.js会拿到对象数组 */} const posts = await res.text(); //console.log(posts); return { props: { posts } }; };
问题现象
控制台显示已成功获取响应,但启用posts.map代码后,浏览器抛出TypeError: posts.map is not a function错误。尝试使用JSON.parse(posts)处理数据,问题依然存在。
修复方案
感谢@Youssouf Oumar的提示,问题根源在于/pages/posts/index.js的getServerSideProps函数中:原代码返回{ props: { posts } },改为直接返回posts后问题解决。
内容的提问来源于stack exchange,提问作者Dinesh Arora
相关产品推荐
相关产品推荐

