在“/pages/blog/index.js”中的代码:
import BlogComponents from "../../components/Blog/blogComponents";
import { listBlogs } from "../../server/mongodb";
const index = async (props) => {
console.log(props)
return (
<div>
<Head>
<title>BLOG TITLE</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta httpEquiv="Content-Type" content="text/html;charset=UTF-8" />
</Head>
<h1>BLOG HEADER</h1>
<BlogComponents />
</div>
);
};
export async function getServerSideProps() {
var blogs = await listBlogs();
try {
return {
props: { blogs }
}
}
catch (error) {
console.log(error);
}
}
export default index;
“../../server/mongodb.js”中的代码:
import mongoose from "mongoose";
// URI for mongodb
const uri = process.env.MONGODB_URI
const options = { useNewUrlParser: true, useUnifiedTopology: true }
// Mongoose Client Promise
mongoose.connect(uri, options)
import {Blog} from "./mongooseModels/blogModel";
export async function listBlogs() {
let blogs = await Blog.find().lean();
//console.log(JSON.stringify(blogs));
return JSON.stringify(blogs);
}
最终目标是获取所有博客文章及其属性,并将其集成到react/nextjs组件中。console.log到index.js中的“props”参数返回:
{
blogs: `[{"_id":"HEXID","title":"Blog Title","author":"ME","date":{"day":"27","month":"January","year":"2021"},"image":"/images/image.jpg","alt":"image alt","summary":"blog summary","content":["blog content "]},{"_id":"61f8c1953907a8bef3dcb4ff","title":"Blog Title 2","author":"ME","date":{"day":"27","month":"January","year":"2021"},"image":"/images/image.jpg","alt":"image alt","summary":"blog summary","content":["blog content"]}]`
}
当前错误为:error -错误:对象作为React子对象无效(找到:[object Promise])。如果你想呈现一个子级集合,请使用数组代替。但是,该页能够接收从getServerSideProps()返回的数据
编辑/解决方案计算出来...错误不是来自getServerSideProps()中的return语句。相反,它来自组件。在准备连接到数据库时,我向组件添加了“async”,这反过来又开始抛出错误。令人失望的是,NextJS不会在返回的错误中告诉你“promise”来自哪里。
2条答案
按热度按时间zhte4eai1#
您的索引博客组件不应声明为
async
。React函数组件是纯同步函数。该组件应该具有同步功能.
sgtfey8w2#
是的,我得到了同样的错误,最初无法弄清楚,因为错误消息相当模糊。
然后我注意到我用async关键字声明了我的react组件,它返回一个Promise,这就是React抱怨的地方。React函数组件不能返回promise对象。否则,在useEffect()中使用async函数可以正常工作。