[英]Objects are not valid as a React child (found: [object Promise]) next js 13
Why do I get this error when I make my page an async function?当我将我的页面设置为异步 function 时,为什么会出现此错误? everything works fine when it isn't an async function. The only difference is that it returns a pending object which isn't what I want.
当它不是异步 function 时,一切正常。唯一的区别是它返回一个挂起的 object,这不是我想要的。
this is how I fetch the data:这就是我获取数据的方式:
const getData = async (id) => {
const res = await fetch({
url: "http://localhost:3000/api/user/getOne",
method: "POST",
credentials: true,
body: {
userId: "637846eb8f36e20663a9c948",
},
});
return res;
}; };
and then this is the page function然后这是页面 function
export default async function Page() {
const profileData = await getData();
useEffect(() => {
console.log(profileData);
}, []);
return(<div><p>Hello</p></div>)
}
I think the problem has to do with the async function and the await.我认为问题与异步 function 和等待有关。 How do I fix this?
我该如何解决?
Move the async in useEffect在 useEffect 中移动异步
export default function Page() {
useEffect(() => {
const getAll= async () => {
const profileData = await getData();
console.log(profileData);
};
getAll(); // run it, run it
}, []);
return(<div><p>Hello</p></div>)
}
Could try the idea as the below code.可以尝试以下代码的想法。
import { useState } from "react";
export default async function Page() {
const [profileData, setProfileData] = useState([]);
async function initDate() {
const response = await getData();
setProfileData(response);
}
useEffect(() => {
initDate();
console.log(profileData);
}, []);
return (<div><p>Hello</p></div>)
}
It's not good to call a function directly inside of the component body in client components because every time with re-rendering of the component, your function gets executed.直接在客户端组件的组件主体内部调用 function 是不好的,因为每次重新渲染组件时,您的 function 都会被执行。
It's better to write them in useEffect with dependencies.最好将它们写在 useEffect 中并带有依赖关系。
If you want to run the function only once, you should use an empty array as the dependency:如果你只想运行一次 function,你应该使用一个空数组作为依赖:
useEffect(() => {
// your code
}, []);
And if you want to run them whenever one or more states change, you should do this:如果你想在一个或多个状态发生变化时运行它们,你应该这样做:
useEffect(() => {
// your code
}, [/* list of the dependencies */]);
So in your case, it would be like this:所以在你的情况下,它会是这样的:
useEffect(() => {
const getProfileData = async () => {
await getData();
}
getProfileData();
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.