对象作为React子对象无效(找到:[object Promise]),如果你想呈现一个子级集合,请使用数组代替,ReactJS

8ehkhllq  于 2023-05-28  发布在  React
关注(0)|答案(2)|浏览(139)

在“/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”来自哪里。

zhte4eai

zhte4eai1#

您的索引博客组件不应声明为async。React函数组件是纯同步函数。

const index = async (props) => { // <-- implicitly returns Promise object
  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 default index; // <-- implicitly returned Promise object

该组件应该具有同步功能.

const index = (props) => { 
  useEffect(() => {
    console.log(props);
  }, [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>
  );
};
sgtfey8w

sgtfey8w2#

是的,我得到了同样的错误,最初无法弄清楚,因为错误消息相当模糊。
然后我注意到我用async关键字声明了我的react组件,它返回一个Promise,这就是React抱怨的地方。React函数组件不能返回promise对象。否则,在useEffect()中使用async函数可以正常工作。

import { useEffect, useState } from 'react';

const url = 'https://api.github.com/userssss'; // /users is correct, /usersssss returns error response.

const FetchTest = () => {
// React component cannot be promise object, must be pure object
const [users, setUsers] = useState([]);
const [isError, setIsError] = useState(false);

const fetchDataExample = async () => {
// but we can have async functions within useEffect()
try {
  let response = await fetch(url);

  if (!response.ok) {
    setIsError(true); // this is a gotcha, because fetch() doesn't treat 4xx and 5xx as errors,
    // thusly, the catch() block will not run if remote resource is not found. So we need to handle the error response like this as well.
    // If Axios is used, this issue is not present and catch() will run on err.
    return;
  }
  // Order of our code in Javascript does matter, thats why we add our error-checking condition first and only after it
  // we write the rest of our code that handles success response
    let users = await response.json();
    setUsers(users);

    console.log(users);

    return users; // do we need to return anything?
} catch (error) {
    setIsError(true);
    console.log(error.message);
}
};

useEffect(() => {
  fetchDataExample();
}, []);

相关问题