错误:当在页面上尝试异步时,对象作为React子对象无效.TSX在nextjs



我正在尝试在页面上使用异步。TSX in nextjs 13 "app"接近并不断得到这个错误:

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
下面是代码示例:
const AsynCfun = async () => {
// reason i use async is because i have await on the http request
const posts = await fetchPosts();
return <div>async print posts...</div>
}
export default function Sidebar() {
return <div>sidebar <AsynCfun/></div> // error...
}

不认为你可以在React中有异步组件,因为渲染是同步的。这里你可以使用state和useEffect。

const AsynCfun = () => {
const [posts, setPosts] = useState();
useEffect(() => {
const fetchAndSetData = async () => {
const data = await fetchPosts();
// do whatever needs to be done on data
setData(data);
};
fetchAndSetData();
});
return <div>async print posts...</div>;
};

然后可以在侧边栏中正常渲染。一件事是useEffect回调不能直接异步,所以你必须创建异步函数并执行任何有状态的操作,如上面所示。

希望有帮助,最好的

最后我找到了答案,我的问题是

客户端组件:

"use client" // its ok to use use client. this component is for FE!
export default function SomeForntEndComponent() {
useEffect(() => {
// usage of useEffect! its a client behaviour!
}, []);
return (<div className="main">
<h1>Sub component = its fe behaviour</h1>
</div>
)
}

服务器端组件(与服务器端fetch同步):

// profile/page.tsx entity file
// it's ok to do a async fetch, this is possible both on front end and backend:
async function fetchData(promptslug:string) { 
let res = await fetch(`http://localhost:3000/api/data`, {
method: "GET",
headers: {
"Content-Type": "application/json",
'Accept': 'application/json'
},
});
if(!res.ok) {
throw new Error('Fail fetch');
}
return res.json();
}

// usage of async on a page component
export default async function Page() {
const data = await fetchData();
return (<div className="main">
<h1>Hello World</h1>
</div>
)
}

代码取自这里:https://lior-amsalem.hashnode.dev/nextjs-error-objects-are-not-valid-as-a-react-child-found-object-promise-if-you-meant-to-render-a-collection-of-children-use-an-array-instead

相关内容

  • 没有找到相关文章

最新更新